Port Authority

Port patterns / Across windows, tabs and reloads

A worker that routes between windows that have never met

The three windows above the router know two things each: their own name, and how to reach the router. None of them has a reference to another, and none of them holds a port of another's. To reach the kitchen, the orders window posts a message to the router addressed to "kitchen". The router looks the name up and passes the message on, with the sender's name attached. Address a name nobody has and the router says so. The router here is a SharedWorker. Each box is a real page of this site, and the link opens a fourth window that can join in.

When you'd use this

A multi-screen web app (like an orders counter, kitchen display, and dispatch board) opens windows in arbitrary order with no parent/opener relationships between them. Each window registers its role with a SharedWorker router and sends messages by role name — getting immediate undelivered feedback if a screen isn't open, or upgrading busy pairs to direct channels.

Code

// every window: say who you are, then address others by name
const { port } = new SharedWorker("/router-worker.js");
port.postMessage({ iam: "orders" });
port.postMessage({ to: "kitchen", text: "two tulip bunches" });
port.onmessage = ({ data }) => show(data.from, data.text);

// the router: a table of names, and nothing else
onconnect = ({ ports: [port] }) => {
  port.onmessage = ({ data }) => {
    if (data.iam) return table.set(data.iam, port);
    const target = table.get(data.to);
    target ? target.postMessage({ from: nameOf(port), text: data.text })
           : port.postMessage({ undelivered: data.to });
  };
};

In practice

// multi-window POS app: orders, kitchen, and driver screens open in any order
const { port } = new SharedWorker("/router-worker.js");
port.postMessage({ iam: "kitchen" });
port.onmessage = ({ data }) => {
  if (data.undelivered) return warn("No window called " + data.undelivered + " is open");
  show(data.from, data.text);
  port.postMessage({ to: data.from, text: "started" });
};
readyButton.onclick = () => port.postMessage({ to: "driver", text: "two tulip bunches ready" });

// inside the SharedWorker router
const table = new Map();
const nameOf = (port) => [...table].find(([, p]) => p === port)?.[0];

How it works

How a message gets from one window to another through the router Windows are drawn with rounded corners and an address bar. The router is a worker, drawn with its corners cut off. Three windows each tell the router their name. The orders window posts a message addressed to kitchen. The router looks kitchen up in its table and posts the message to the kitchen window with the sender's name attached. No line joins one window to another. /route.html?name=orders /route.html?name=driver /route.html?name=kitchen Orders window knows: its name, the router Driver window knows: its name, the router Kitchen window knows: its name, the router Router a SharedWorker, or a Service Worker orders→ window 1 kitchen→ window 2 driver→ window 3 2. looks the name up 1. posts to the router { to: "kitchen", text } any window can, the same way 3. passes it on { from: "orders", text }
Every message goes to the router and comes out of it. No line joins one window to another.

Most patterns on this site introduce two parties and step away. Sometimes you want the worker to stay in the middle on purpose so windows don't need to track who else is open, or you want a SharedWorker to introduce tabs directly into a peer-to-peer mesh once they join.

The router itself is just a map from role names to ports. A window registers by announcing its name, then sends { to, text }. The router looks up to, stamps the real sender name from the incoming port (preventing spoofing), and forwards the message. If two windows start talking heavily, the same SharedWorker can upgrade them to a direct channel by minting a MessageChannel and sending each an end.

As a SharedWorker, the table holds live ports and lasts as long as at least one tab is open. As a ServiceWorker (see the second demo below), there are no long-lived ports — the table stores client IDs and rebuilds itself with a roll call whenever the browser wakes it from idle.

Because every message passes through one place, the router can queue messages for windows that aren't open yet, fan out to every window sharing a role, or coordinate leader election across tabs (see OPFS DB leader for combining this with exclusive OPFS writes).

Step by step

What each press of Next does in the demo above.

  1. Register the three windows. Each window connects to the SharedWorker and registers its name. None of them has a line to another window.
  2. Orders: send to the kitchen. The orders window posts to the router, addressed to "kitchen". The router looks the name up and passes it on.
  3. Kitchen: send to the driver. The kitchen does the same for the driver. It has never seen the driver's window.
  4. Driver: send to orders. And the driver reaches orders. Every message went through the middle.
  5. Orders: send to the florist. Nobody registered that name. The router tells the sender it could not be delivered.
  6. Close the kitchen. The kitchen's window is destroyed. The router notices and takes it out of its table.
  7. Orders: send to the kitchen. The same message as before. This time there is nobody to give it to.

What you can build with it

Built and running below.

One tab does the background job, and another takes over when it closes

Electing one tab as the leader for a background job and automatically promoting another when it closes.

Three tabs of this site are open in the boxes below. A shared worker holds a port to each, keeps the list of who is here, and names one the leader. Only the leader runs the sync job. Close it, and the worker notices through a lock the tab was holding, promotes the tab that has been here longest, and tells everyone. The link opens a fourth tab for real.

Code

// each tab
navigator.locks.request(myName, () => new Promise(() => {}));   // held until this tab dies
port.postMessage({ join: true, lock: myName });
port.onmessage = ({ data }) => { iAmLeader = data.lead; };

// the worker
navigator.locks.request(lock, () => leave(port));   // runs when the tab has gone

Step by step

What each press of Next does in this demo.

  1. Close the leader. The leading tab is destroyed. The worker gets its lock, and promotes the next tab.
  2. Close the leader. And again. The last tab left is the leader.

A list that stays the same in every tab, with no server

Keeping live state (like a shopping list or draft notes) synced across tabs in a SharedWorker with zero server round trips.

The two boxes are two tabs of this site, each showing a shopping list. Add an item in one and it appears in the other. Tick it in the other and it is ticked in the first. The list lives in a shared worker that holds a port to every tab. Nothing is sent to a server, and nothing is written to storage. The checkboxes in the boxes work too, and the link opens a third tab for real.

Code

// every tab
const port = new SharedWorker("/sync-worker.js").port;
port.onmessage = ({ data }) => render(data.list);
addButton.onclick = () => port.postMessage({ add: true });

// the worker
onconnect = ({ ports: [port] }) => {
  ports.add(port);
  port.onmessage = ({ data }) => { change(list, data); for (const p of ports) p.postMessage({ list }); };
};

Step by step

What each press of Next does in this demo.

  1. Tab one: add an item. Tab one tells the worker. The worker tells every tab.
  2. Tab one: add an item. A second item, in both tabs.
  3. Tab two: tick the first item. Tab two ticks it, and it is ticked in tab one.

The same router as a Service Worker, which forgets and asks again

Windows of one app opening and closing in any order while still addressing each other by role.

A Service Worker can do the same job with no ports at all. Each window posts to the Service Worker, and the Service Worker reaches the others through its list of open windows. There is one difference that matters. A browser stops a Service Worker when it is idle, and it wakes with an empty table. So when this one cannot place a name, it asks every open window to say who it is, and then tries again. The button that makes it forget stands in for the browser stopping it, which a page cannot ask for.

Code

// every window
registration.active.postMessage({ iam: "orders" });
registration.active.postMessage({ to: "kitchen", text: "two tulip bunches" });
navigator.serviceWorker.onmessage = ({ data }) =>
  data.rollcall ? registration.active.postMessage({ iam: "orders" }) : show(data.from, data.text);

// the Service Worker
onmessage = async (event) => {
  let target = await clients.get(table.get(event.data.to));
  if (!target) { await rollCall(); target = await clients.get(table.get(event.data.to)); }   // woke up empty?
  target.postMessage({ from: nameOf(event.source.id), text: event.data.text });
};

Step by step

What each press of Next does in this demo.

  1. Register the three windows. Each window tells the Service Worker its name. No MessagePorts are used.
  2. Orders: send to the kitchen. The orders window posts to the Service Worker, which finds the kitchen's window and passes the message on.
  3. Make the Service Worker forget. Its table is emptied, as it would be if the browser had stopped it.
  4. Kitchen: send to the driver. The Service Worker knows nobody. It asks every window to say who it is, rebuilds its table, and delivers.
  5. Orders: send to the florist. It asks again, nobody answers to that name, and the sender is told.

Messages kept in the worker until the window they are for opens

A message queue in the worker holding messages for a window that hasn't opened yet.

The orders and kitchen windows are open. The driver's window is not. When either of them sends to "driver", the shared worker finds no such name in its table and keeps the message in a list under that name. When a window opens and says it is the driver, the worker hands over everything in the list, oldest first. After that it passes messages straight through. The senders do the same thing in both cases. The list is in the worker's memory, so it lasts for as long as at least one window of the app stays open.

Code

// the worker
const table = new Map();   // name -> port
const held = new Map();    // name -> messages waiting for that name

port.onmessage = ({ data }) => {
  if (data.iam) {
    table.set(data.iam, port);
    for (const message of held.get(data.iam) || []) port.postMessage(message);
    held.delete(data.iam);
  }
  if (data.to) {
    const target = table.get(data.to);
    const message = { from: nameOf(port), text: data.text };
    target ? target.postMessage(message)
           : held.set(data.to, [...(held.get(data.to) || []), message]);
  }
};

Step by step

What each press of Next does in this demo.

  1. Orders: send to the driver. No window is called driver. The worker keeps the message.
  2. Kitchen: send to the driver. A second message for the driver, from a different window. The worker is now holding two.
  3. Open the driver's window. The new window tells the worker its name. The worker hands over both messages, in the order they were sent.
  4. Orders: send to the driver. The driver is open now, so this one is passed straight on.

One message to every window with a role

Addressing every window with a role at once, such as every open editor tab.

Each window tells the worker its name and its role. Two of these are editors and one is a preview. The settings window does not know how many editors are open or what they are called. It posts one message addressed to the role "editor", and the worker sends a copy to every window that gave that role. Open another editor and it is included from then on. Close one and the worker takes it out of the table, so the next message goes to the ones that are left.

Code

// each window
port.postMessage({ iam: "editor-1", role: "editor" });

// the settings window
port.postMessage({ toRole: "editor", text: "use font size 18" });

// the worker
if (data.toRole) {
  for (const [, w] of table)
    if (w.role === data.toRole && w.port !== port)
      w.port.postMessage({ from: nameOf(port), text: data.text });
}

Step by step

What each press of Next does in this demo.

  1. Settings: tell every editor. One message, addressed to the role "editor". Both editors get it. The preview has a different role and gets nothing.
  2. Open a third editor. Another window opens and gives the same role.
  3. Settings: tell every editor. The same call as before. This time three windows get it.
  4. Close editor 1. The window is destroyed. The worker notices and takes it out of its table.
  5. Settings: tell every editor. Two editors are left, and those two get it.

A request sent to whichever open window offers the tool

A hub that routes each request to whichever open window currently provides that tool.

Windows tell the worker which tool they offer. The shop window asks for a tool by what it does, "print-label" or "find-route", and never names a window. The worker looks for an open window that offers it, passes the request on, and that window answers the shop by name through the same worker. Close the label printer and the request has nowhere to go, and the shop is told. Open a different window that offers the same tool and the same request reaches that one. The hub on this site does this between sites on different origins.

Code

// a window that offers a tool
port.postMessage({ iam: "label-printer", tool: "print-label" });
port.onmessage = ({ data }) =>
  data.job && port.postMessage({ to: data.from, text: print(data.text) });

// the shop: asks for the tool, not for a window
port.postMessage({ need: "print-label", text: "order 1" });

// the worker
if (data.need) {
  const found = [...table].find(([, w]) => w.tool === data.need);
  found ? found[1].port.postMessage({ from: nameOf(port), job: data.need, text: data.text })
        : port.postMessage({ nobody: data.need });
}

Step by step

What each press of Next does in this demo.

  1. Shop: ask for a label. The shop asks for "print-label". The worker finds the window that offers it. The answer comes back to the shop.
  2. Shop: ask for a route. A different tool, so the worker picks a different window.
  3. Close the label printer. The only window that prints labels is destroyed.
  4. Shop: ask for a label. No open window offers that tool now. The worker tells the shop.
  5. Open the back office. A different window opens. It also offers "print-label".
  6. Shop: ask for a label. The same request as before. It goes to the back office.

Things to try

  • Open a fourth window from the link (called florist), then send from Orders to the florist again.
  • Close the kitchen window and send to it — the Web Lock drops and the router removes it from the table immediately.
  • In the Service Worker version below, make it forget its table and send again to watch the roll call rebuild it.

Gotchas

  • The router sees every message unless it upgrades two peers to a direct MessageChannel.
  • If you only need to broadcast tiny JSON events to all same-origin tabs without transferables or 1-to-1 routing, BroadcastChannel is simpler and needs no worker.
  • Inside a cross-site iframe, a SharedWorker is partitioned by the top-level site.
  • A Service Worker loses all in-memory state whenever the browser stops it when idle — rebuild from open clients or persist in IndexedDB.
  • Names here are last-writer-wins; decide upfront whether a duplicate name replaces, fails, or joins a group.
  • Holding a Web Lock for tab presence can block bfcache in some browsers; release on pagehide if bfcache matters.

Measured

Chromium 157: three same-origin frames exchange messages through a SharedWorker, and through a Service Worker via clients.get. After clearing the Service Worker's table, a single roll call rebuilds it. 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.

SharedWorker
A worker that every page on the same origin can connect to. Each page that connects gets a port to it. MDNHTML Standard
MessageChannel
Makes a new pair of joined ports, port1 and port2. MDNHTML Standard
Origin private file system
Origin-scoped file storage hidden from the user's normal filesystem. A worker can open a file in it for fast, exclusive synchronous access. MDNFile System Standard
Service workers
A worker the browser starts for an origin to handle its network requests and events, even when no page is open. The browser stops it when it is idle. MDNService Workers
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
Web Locks
Lets pages and workers on one origin take a named lock, so that only one of them does a piece of work at a time. MDNWeb Locks
Transferable objects
Objects that can be moved to another page or worker instead of copied. After the move the sender can no longer use them. The transfer list is the argument to postMessage that names them. MDNHTML Standard
BroadcastChannel
A named channel that every page and worker on the same origin can join. A message goes to all of them. It cannot carry ports or other transferable objects. 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
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
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
pagehide event
An event fired when a page is being left: closed, navigated away from, or put in the back/forward cache. MDNHTML Standard
Clients.get()
Looks up one page that a service worker controls, by its id. MDNService Workers

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