Port Authority

The guide to message ports

Everything this site has worked out about sending things between pages, frames, workers and origins. Each claim links to something running that shows it. Where a line says "measured", it came from the lab, in the Chromium this was built with. Other browsers are being filled in as people run it, and the results page shows where they differ.

1. The model in five sentences

  1. new MessageChannel() makes two ports that are the two ends of one private wire.
  2. Whatever is posted into one port comes out of the other, wherever that other port now is.
  3. A port can be sent through postMessage, including through another port, and after that the sender no longer has it.
  4. Nothing else identifies a port: no name, no address, no way to look one up. To use a wire you must have been handed an end of it.
  5. So holding a port is the permission to use it, and passing a port on is how permission is given.

Running: a channel is two ends of one wire, introduce two strangers, then leave.

2. Where a message can go

These calls take a transfer list, so a port, and anything a port can carry, can land there.

CallReachesWorth knowing
window.postMessageAny frame, popup or opener, on any originThe only door between origins inside a browser. You need a reference to the window: one you opened, your opener, or a frame.
port.postMessageThe other end of the wireWorks the same wherever the two ends have travelled.
worker.postMessageA dedicated worker, and backThe worker's thread owns what it receives. The page can stall without stalling it.
sharedWorker.portOne worker shared by every tab of an originInside a frame on another site it is partitioned: a different worker per top-level site.
serviceWorker.postMessage, client.postMessageThe origin's service worker, and from it any open window of the originThe worker is stopped when idle and forgets its ports. Have it ask for a new one when it wakes.
audioWorkletNode.portThe audio rendering threadMeasured: ports, buffers and streams arrive and work. Almost nothing else can be rebuilt there.
structuredClone(v, { transfer })The same contextUseful for detaching a buffer, and for testing what is cloneable.

These take data only. They copy, and they refuse anything that has to be moved.

  • BroadcastChannel, IndexedDB, history.state and storage events. Measured: a port is refused by all three that could be tested.
  • WebSocket, WebRTC data channels and WebTransport carry bytes and strings. They are how you leave the machine. A port at each end with a bridge between gives you a port that crosses machines.

Outside the browser's own pages, the same idea appears as real ports between an Android app and its WebView, between an extension's content script and the page it runs in, and between Electron's processes. This site has not tested those.

Running: the lab sends to thirteen of these places. A SharedWorker as the exchange. A tab that is a web server for other tabs. A shared worker holding the only socket. A worker sending notes to the audio thread.

3. What can be sent

Two different things happen, and it matters which. Something in the transfer list is moved: the sender loses it. Anything else is copied: both sides hold one. Moved things cannot be stored, because storing is copying.

KindHowMeasured, to a frame on another origin
MessagePortMovedWorks, and works again from there to a worker inside that frame.
ArrayBufferMovedWorks. The sender's buffer drops to zero bytes. 64 MB in a few milliseconds.
ReadableStream, WritableStream, TransformStreamMovedWork. The data keeps flowing through the context that sent the stream.
OffscreenCanvasMovedWorks, including one tied to a canvas in your page. Another origin paints in your page.
ImageBitmapMoved or copiedWorks.
VideoFrame, AudioData, EncodedVideoChunkMoved or copiedArrive unreadable. They do work to a worker and to a sandboxed frame. Video through a sandboxed filter.
RTCDataChannel, MediaSourceHandleMovedArrive unreadable. They work to a worker and to a sandboxed frame.
MediaStreamTrackMoved, by the specificationRefused everywhere. A live camera track cannot be handed over yet. Frames can.
CryptoKeyCopiedWorks, including a key nobody can read. The receiver can use it and keep it for good.
Blob, File, ImageData, errors, geometry, plain dataCopiedWork. Maps, sets, dates, big integers and cycles survive.
RTCCertificate, CropTargetCopiedWork.
File system handlesCopiedArrive unreadable. They work within the origin.
SharedArrayBuffer, WebAssembly.Module, shared WebAssembly.MemoryShared, or copiedStay within the origin. Shared memory also needs a cross-origin isolated page.
PromiseNeitherNot refused. It arrives as an empty object, silently.
Functions, DOM nodes, symbols, proxies, URL, Response, MediaStream, AbortSignal, workersNeitherRefused with DataCloneError. A port can stand in for a function.

The full table has 45 kinds against 13 destinations, and each test uses the thing where it lands, because arriving is not the same as working. Run it in your browser or see what others reported.

4. Ports as permissions

Because a port can only be used by whoever holds it, the ordinary moves of access control become ordinary moves with ports.

  • Grant: send a port.
  • Introduce: make a channel, send one end to each of two parties, and keep nothing. They now talk without you, and removing you changes nothing. Running.
  • Reply to exactly one asker: send a fresh port with each question, and answer on it. No request ids, and no way to answer the wrong party. Running.
  • Give less than you have: do not pass on your own port. Make a new channel, keep one end, and forward only what you choose to. The limit lives with you and the holder cannot widen it. Running.
  • Revoke: close your end. The other side is not told, so a client should treat silence as the answer.
  • Delegate along a chain: each holder passes on a narrower port of its own. A signing port narrowed to three orders.

There are no accounts, tokens or lists of who is allowed in any of these. What you hold is what you may do.

5. Streams

  • A stream sent down a port is read on the far side while the near side is still producing it, with back-pressure: a slow reader slows the source. Running, and across three origins.
  • A stream has a direction, and each direction can be given away separately. A readable alone is permission to listen. A writable alone is permission to speak. Running, between real sites.
  • The owner keeps the switch. Close the controller and the listener is told the feed has ended. Error the sink and the next write fails.
  • A transform has two ends and both can be given away, which makes a transform a service: mine.pipeThrough(theirs), where theirs runs on another origin. Running.
  • A network connection is two streams. Hand them to a context that has no network access and it can talk on that one connection and no other, until you close it. Running.
  • A stream does not survive the context it was passed through. If a middle party forwards a stream and then goes away, the reader stalls with no error. Send streams down a direct port. Running.

6. Threads

  • A port given to a worker belongs to the worker's thread. Two workers introduced to each other keep talking while the page is frozen. Running.
  • A canvas whose drawing surface has been transferred is painted without the page too, so a worker can show its state while the page is stuck.
  • With shared memory, a worker can post a question down a port and block on that line until the answer is written. Synchronous code can call anything asynchronous, a person included. Running, in the isolated room.
  • A service worker can answer a fetch by asking a port, which turns a tab into the server for a set of URLs. Running.
  • The other end of that port can be on another origin. Introduce your service worker to another site and that site is mounted at a path on yours, streamed bodies included. Measured: a ReadableStream made in a frame on another origin is accepted by the service worker as a response body, and is read while it is still being written. What is mounted runs as your origin. Running.
  • The audio thread accepts a port. Give a worker the other end and it drives sound with no help from the page. Measured: 13 notes in a 3 second freeze, at one every 230 ms, so none were lost. Running.
  • A shared worker can hold the one connection a site needs, with a port to each tab. An answer goes back down the port of the tab that asked. Running.

7. Keys

There are two ways to let another origin use a key, and they are not alike.

  • Send the key. A non-extractable CryptoKey can be posted to another origin. Measured: it arrives, it signs, and it still cannot be read. But it is a copy. The receiver can store it in its own IndexedDB and keep using it after you have destroyed yours. Running, between real sites.
  • Send a port that uses the key. The key stays where it was made. The port can be limited to certain messages, counted, passed on in a weaker form, and closed. Running.

For delegating authority you mean to be able to take back, send the port.

8. Making a port last

  • A port cannot be saved. Leave it with a SharedWorker in pagehide and collect it on the next load. Create the worker with extendedLifetime: true, or it dies with its last page. Messages sent meanwhile wait in the port. Running.
  • A port survives its page being torn off into a new window, if it is handed to that window. Running.
  • For anything that must outlive every tab, a port is the wrong tool. Keep the durable part on a server and make fresh ports when a page opens. This site's hub keeps its registry on a server for that reason.

9. Further than one browser

  • Two tabs that are not related cannot pass a port: neither has a reference to the other. A server can introduce them, and they can then open a WebRTC data channel between themselves. Wrap each end in a MessageChannel and both sides hold what looks like an ordinary port. The hub does this when a tool's site is already open.
  • That bridge carries JSON only. Ports and streams cannot ride on it, where they can on a real port.
  • The same bridge works between devices. A pairing code names a meeting place on the server, which passes the handful of messages WebRTC needs and then carries nothing. Each device holds a port, and can hand it on: a phone ends up pressing buttons in a sandboxed frame on a laptop that was given a port and nothing else. Running. Measured between two pages on one computer. Between two networks it depends on both being able to reach each other, and there is no relay for when they cannot.

10. What will bite you

  • A port attached with addEventListener stays silent until you call port.start(). Setting onmessage starts it for you.
  • Messages posted before the other side is listening are not lost. They wait in the port.
  • Nothing tells you the other end has gone. A close event is specified, and the Chromium this was built with does not fire it. On one origin, hold a Web Lock in the page and wait on it elsewhere. Across origins, ping.
  • A transferred object is gone from the sender. Post it twice and the second call throws.
  • A port in the transfer list turns up in event.ports. Anything else in the transfer list that is not also somewhere in the message is moved and then lost.
  • When a message cannot be rebuilt on arrival, the receiver gets messageerror and the sender gets nothing. Many kinds fail this way between origins, and to shared workers and service workers. Listen for it.
  • A write to a transferred stream can report success before the far side has refused it. The failure arrives on the next write.
  • Shared workers and service workers inside a frame on another site are partitioned by the top-level site, so a hidden frame cannot be a meeting point for the whole web. A window of its own can.
  • A page that is cross-origin isolated cannot keep a reference to a window that is not. It gets shared memory and loses popups to other origins.
  • A person who has asked for reduced motion still needs to see that something happened. This site skipped its animations for them and looked broken.

11. What is still open

  • Safari and Firefox. Everything marked "measured" is Chromium until the results page says otherwise.
  • WebTransport streams. They are ordinary streams and should move like any other, which would let one origin open a session and lend another a single stream of it. Not measured: it needs a server this site does not have yet. The WebSocket version is running.
  • Why video frames and data channels reach a sandboxed frame and not a frame on a real second origin.
  • Why the shared worker stops answering part-way through the isolated lab.
  • Ports to a native app and to an extension. A port to another machine is running, tested between two pages on one computer and not yet between two networks.