Port Authority

Port patterns / Across windows, tabs and reloads

Keep a port across a page reload

You can't save a MessagePort in IndexedDB, sessionStorage or history state — ports can only be moved, never copied. Instead, park it with a SharedWorker on pagehide and withdraw it when the page loads again. With extendedLifetime: true (Chromium 148+), the worker survives even when the reloading page was its only client. The feed never notices, and ticks sent mid-reload buffer inside the port with zero gaps.

When you'd use this

A notes app is connected via a MessagePort to a user's calendar or local tool picked through a chooser. When the user hits reload, the page deposits the port into a SharedWorker during pagehide and withdraws it on the next load — avoiding another permission prompt and keeping messages sent mid-reload intact. Fall back cleanly to reconnecting after a crash or on browsers without extendedLifetime: true.

Code

const bank = new SharedWorker("/bank.js", { extendedLifetime: true });
addEventListener("pagehide", () => bank.port.postMessage({ deposit: key }, [port]));

// next load
bank.port.postMessage({ withdraw: key });
bank.port.onmessage = ({ data, ports }) => data.found ? resume(ports[0]) : connectAgain();

In practice

// /bank.js (SharedWorker): park ports under a per-tab key
const kept = new Map();
onconnect = ({ ports: [client] }) => {
  client.onmessage = ({ data, ports }) => {
    if (data.deposit) return kept.set(data.deposit, ports[0]);
    const port = kept.get(data.withdraw);
    kept.delete(data.withdraw);
    client.postMessage({ found: !!port }, port ? [port] : []);
  };
};

// in the page: keep a per-tab token in sessionStorage
const key = sessionStorage.portKey || (sessionStorage.portKey = crypto.randomUUID());
const resume = (p) => { port = p; port.onmessage = (e) => showEvent(e.data); };
bank.port.onmessage = ({ data, ports }) => data.found ? resume(ports[0]) : connectAgain();
addEventListener("pageshow", (e) => { if (e.persisted && !port) bank.port.postMessage({ withdraw: key }); });

How it works

A MessagePort dies with its page, and you can't save it in IndexedDB, sessionStorage, or history state because ports can only be moved, never copied. You can park it in a SharedWorker.

During pagehide, the unloading page transfers its port to the SharedWorker under a key. When the page finishes reloading, it connects back to the worker and withdraws the exact same port. Any ticks sent during the reload simply buffer inside the port.

Creating the worker with extendedLifetime: true (currently Chromium 148+) keeps it alive briefly even when the reloading page was its only client.

Step by step

What each press of Next does in the demo above.

  1. Connect the feed to the frame. Transfers a live feed port into the frame and ticks start arriving.
  2. Reload the frame. On pagehide, the frame parks its port in the SharedWorker bank, reloads, and withdraws it with zero gaps.

What you can build with it

Built and running below.

Replace a running widget with its next version, and keep its connection

Handing a live port from an old version of a page to a freshly loaded one.

Version 1 of a chat widget is holding a port to a service that sends it numbered messages. Version 2 is ready. Loading it the usual way would mean dropping the connection and making another, and losing whatever arrived in between. Here version 1 stops listening, hands its port to version 2, and is removed. Messages that arrive during the swap wait in the port. The service is never told that anything changed.

Code

// version 1, when asked to step aside
port.onmessage = null;                                       // stop reading: what arrives now will wait
parent.postMessage({ handover: true, last }, "*", [port]);

// version 2
port.onmessage = ({ data }) => { /* carries on from last + 1 */ };

Step by step

What each press of Next does in this demo.

  1. Connect version 1 to the service. The service starts sending numbered messages down a port.
  2. Load version 2 and hand over. Version 1 gives up its port and is removed. Version 2 picks up at the next message.

A connection granted once, kept across every page of a site

Keeping a live cross-origin connection alive across multi-page navigations.

The box on the right is a small site with three pages, and each link is a real navigation that throws the old page away. On the first page it was granted a port to an order feed on another origin. On the way out of each page it leaves that port with a shared worker, and on the way in it collects it. The feed keeps sending throughout. Updates sent while no page existed wait in the port, so none are missed.

Code

// on every page of the site
const bank = new SharedWorker("/bank.js", { extendedLifetime: true });
bank.port.postMessage({ withdraw: "orders" });                 // is one waiting for me?
bank.port.onmessage = ({ ports }) => ports[0] ? resume(ports[0]) : askToBeGranted();
addEventListener("pagehide", () => bank.port.postMessage({ deposit: "orders" }, [port]));

Step by step

What each press of Next does in this demo.

  1. Go to the next page. A real navigation, from Shop to Basket. The new page collects the port.
  2. Go to the next page. And again, to Account. The count has no gaps.

Already running elsewhere

Things to try

  • Click Try to store a port in IndexedDB to see the browser's DataCloneError.
  • Reload the frame repeatedly and check the gap count: 0 gaps and 0 duplicates.

Gotchas

  • extendedLifetime: true is currently Chromium-only (148+). Without it, the SharedWorker dies with its last page unless another tab stays open.
  • If the browser restores the page from bfcache, top-level scripts don't re-run — handle pageshow when event.persisted is true to withdraw the port back.
  • pagehide won't run if a tab crashes or gets killed by the OS.
  • SharedWorker is partitioned inside cross-site iframes, so this only works for your own origin's pages.

Measured

Chromium 157: the feed count shows zero gaps across reloads of the receiving frame. Other browsers are being filled in from the lab's results.

References

The web platform features this page mentions, with what each one is, its documentation on MDN and the specification that defines it.

MessagePort
One end of a message channel. Whatever is posted into it comes out of the other end, and it can be sent to another page, frame or worker. MDNHTML Standard
IndexedDB
A database in the browser that belongs to one origin. It can store most things that can be posted, including a CryptoKey. MDNIndexed Database API
sessionStorage
A small store of strings that belongs to one tab and one origin, and is emptied when the tab closes. MDNHTML Standard
SharedWorker
A worker that every page on the same origin can connect to. Each page that connects gets a port to it. MDNHTML Standard
pagehide event
An event fired when a page is being left: closed, navigated away from, or put in the back/forward cache. MDNHTML Standard
SharedWorker extendedLifetime
An option in Chrome that keeps a shared worker running for a short time after its last page has closed. Chrome for Developers
DataCloneError
The error thrown when something that cannot be copied or moved is posted. MDNWeb IDL
Back/forward cache
The browser keeps a page it has left, whole and paused, so that Back shows it at once. A page in the cache receives no messages. MDNHTML Standard
<iframe>
An element that shows another page inside this one. The inner page can be on a different origin, and the two can only talk by posting messages. MDNHTML Standard

For more, see Further reading: articles, talks, papers, libraries and the specifications, collected in one place.