Port Authority

Port patterns / Across windows, tabs and reloads

Tear a live widget off into its own window

A MessagePort keeps working no matter which window holds it. The meter below is driven by a feed on another origin. Tear it off and the port transfers straight into a new popup window, which picks up on the very next tick without reconnecting. Dock it back and the popup returns the port.

When you'd use this

A live dashboard or chat widget gets its updates over a MessagePort, and the user wants to pop that panel out onto a second screen. Opening a popup and transferring the port straight into it keeps the stream ticking with zero re-authentication and zero missed events; closing the popup hands the port straight back.

Code

const win = window.open("/meter.html", "", "popup");
// once it says it is ready
win.postMessage({ feed: port }, location.origin, [port]);

In practice

// trading dashboard letting users pop a live ticker out onto a second monitor
// /meter.html in the popup: announce ready, then take over the live port
let port = null;
opener.postMessage("ready", location.origin);
addEventListener("message", (event) => {
  if (event.origin !== location.origin || !event.data.feed) return;
  port = event.data.feed;
  port.onmessage = (e) => showPrice(e.data);
});
// popup closing: return the port to the opener
addEventListener("pagehide", () => { if (port) { opener.postMessage({ back: true }, location.origin, [port]); port = null; } });

// host page hands over the port on "ready" and catches it on return
addEventListener("message", (event) => {
  if (event.source !== win || event.origin !== location.origin) return;
  if (event.data === "ready" && port) { win.postMessage({ feed: port }, location.origin, [port]); port = null; }
  if (event.data.back) { port = event.ports[0]; port.onmessage = (e) => showPrice(e.data); }
});

How it works

This page holds a port to a feed running on another origin. When you tear the meter off, the page opens a popup window and transfers its end of the port straight into that popup. The feed keeps ticking into the exact same channel — it neither knows nor cares which window now holds the other end.

No state gets serialised and nothing reconnects. Any ticks posted mid-transfer wait inside the port's queue and land cleanly in the popup.

Docking it back just transfers the port in the opposite direction.

Step by step

What each press of Next does in the demo above.

  1. Connect to the feed. Transfers a feed port to the other origin and live ticks start arriving.

What you can build with it

Built and running below.

Float a tool above every other window, without moving its port

Moving an active tool from a sidebar into Document Picture-in-Picture.

Document Picture-in-Picture gives a page a small window that stays on top of everything. It differs from tearing off into a popup in one useful way: the new window has no script of its own. This page's script keeps running it. So the meter's element moves into the floating window and the port stays exactly where it was. Close the floating window and the element comes home. This needs Chrome or Edge on a desktop, and a real press of the button.

Code

const pip = await documentPictureInPicture.requestWindow({ width: 260, height: 150 });
pip.document.body.append(meter);          // the element moves
port.onmessage = ({ data }) => { meter.textContent = data; };   // the port and its listener do not
pip.addEventListener("pagehide", () => sidebar.append(meter));

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

Handing a live connection from one window or worker to its replacement without dropping state (see also live worker hot-swap).

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.

Already running elsewhere

Things to try

  • Connect to the feed, tear the widget off, and watch the popup continue counting with zero gap.
  • Click Put it back (or close the popup) and watch the host page handle the return.

Gotchas

  • Popup windows require user activation (a click) and are mainly a desktop pattern; strict Cross-Origin-Opener-Policy severs window.opener.
  • If the popup crashes or is force-closed, pagehide may not run — watch win.closed so you know when to recover.
  • If the host page holding the feed iframe reloads, that iframe dies unless the feed runs in its own window or worker.

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
pagehide event
An event fired when a page is being left: closed, navigated away from, or put in the back/forward cache. 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.