Port patterns / Hot-swapping, wiretapping and liveness
Pair a work port with a health port to detect silence
A MessagePort won't fire an event when its other end dies — posting into it silently queues into thin air. Send a second port alongside your work port solely for health checks (either request/reply pings or one-way heartbeats, plus a pagehide goodbye or a same-origin Web Lock). Your work protocol stays clean, and three missed pings let you treat the far side as gone.
When you'd use this
A checkout page embeds a third-party delivery quote iframe. If that iframe crashes, hangs, or navigates away, messages posted into the data port vanish without an error. Pairing a dedicated health port lets you catch normal unloads in milliseconds via pagehide and silent hangs after three missed pings, falling back cleanly instead of stranding the user.
Code
import { watch, answer } from "/alive.js";
// this page: work port + dedicated health port
const data = new MessageChannel(), health = new MessageChannel();
frame.contentWindow.postMessage("ports", origin, [data.port2, health.port2]);
const watcher = watch(health.port1, { every: 1000, misses: 3,
onState: (state) => state === "silent" || state === "closed" ? giveUp() : null });
// the far side
onmessage = (e) => {
if (e.origin !== expectedOrigin) return;
const [data, health] = e.ports;
data.onmessage = (m) => data.postMessage(price(m.data)); // zero health logic here
answer(health); // answers pings, and says goodbye on pagehide
};
In practice
// checkout page watching a third-party shipping-quote iframe
const watcher = watch(health.port1, { every: 1000, misses: 3,
onState: (state) => state === "silent" || state === "closed" ? giveUp() : null });
data.port1.onmessage = (e) => { deliveryPrice.textContent = e.data; };
postcode.onchange = () => data.port1.postMessage(postcode.value);
function giveUp() {
watcher.stop(); data.port1.close(); health.port1.close();
courierFrame.remove();
deliveryPrice.textContent = "Delivery quotes temporarily unavailable — you can still order.";
}
How it works
A MessagePort gives you no connection state and no close event. If the far end closes, navigates, crashes, or hangs, postMessage silently succeeds into thin air.
Pairing a second port solely for health checks keeps your work protocol completely clean. You can run either request/reply pings (caller pings, callee pongs) or one-way heartbeats (each side beats on a timer and listens to the other — half the traffic, mutual detection). In both models, pages also post an immediate bye message from pagehide so normal closes are caught in a few milliseconds, while missed pings catch silent crashes, hangs, and port.close().
For same-origin contexts, you can also pair this with a Web Lock: have the far side hold a unique named lock forever and queue for the same lock on your side. The browser releases the lock within milliseconds if the frame unloads or the worker terminates/crashes (try the live signal benchmark to compare all four detectors).
Why not a native close event? One was added to the HTML standard in 2024, never shipped on by default in any browser, and was removed again in October 2026 because it exposed garbage-collection timing.
Step by step
What each press of Next does in the demo above.
- Connect. This page creates two channels and transfers both a work port and a health port to the florist's origin. Pings start immediately on the health port.
- Ask the price of tulips. The work message and reply travel on the teal work port — the health port isn't touched.
- Far side: busy for 5 seconds. The far side blocks in a loop. One missed ping marks it late, three mark it silent; once the loop finishes it recovers to alive.
- Remove the far side. The frame unloads and sends a goodbye on the health port as it goes, so this page detects it straight away.
What you can build with it
Already running elsewhere
- Showing users immediately when a connected tool or plugin goes away instead of hanging forever. See the demo at the top of this page.
- Detecting hung workers so you can terminate and replace them cleanly. See a worker restarted when it stops answering.
Things to try
- Make the far side busy for 5 seconds and watch it transition Late → Silent → Alive again once it unblocks.
- Close the far side's ports directly: with no
pagehide, three missed pings catch it cleanly. - Run the 5×5 disconnect signal benchmark on the patterns page to time every signal in your browser.
Gotchas
- Never treat a single missed ping as death — GC pauses and busy main threads cause brief delays; count consecutive misses.
- Browsers throttle timers on hidden tabs down to ~1/minute; include
document.hiddenin pongs/beats so the watcher widens its timeout (/alive.jshandles this automatically). pagehidewithevent.persisted === truemeans the page entered bfcache and may return — treat it as paused rather than dead.- Health pings prove the thread's event loop is responsive, not that every individual work job succeeded — put timeouts on work requests too.
Measured
Chromium 153: pagehide goodbye arrives in <10 ms; a 5-second hung frame goes late at 1 s, silent at 3 s, and recovers immediately when it unblocks. 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
- pagehide event
- An event fired when a page is being left: closed, navigated away from, or put in the back/forward cache. 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
- <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
- MessagePort.postMessage()
- Sends a message through a port. A second argument lists the objects to move instead of copy. MDNHTML Standard
- 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
For more, see Further reading: articles, talks, papers, libraries and the specifications, collected in one place.