Port Authority

Port patterns / Streams, zero-copy data and RPC

Pass a function to another origin

You can't structured-clone a function, but a MessagePort can stand in for one. Wrap the function in a channel, transfer the other end, and the receiver gets something it can call — and you can pass callback arguments the same way. Close your end and the function stops working for them. This is how Comlink works underneath.

When you'd use this

A photo app embeds a third-party batch resizer and wants it to drive a native progress bar without giving the iframe DOM access. You wrap onProgress in a channel and transfer the far end; the iframe calls it like a normal function, and calling revoke() disconnects it cleanly if the user navigates away.

Code

const lend = (fn) => {
  const { port1, port2 } = new MessageChannel();
  port1.onmessage = (e) => { if (Array.isArray(e.data)) fn(...e.data); };
  return { port: port2, revoke: () => port1.close() };   // send port, keep revoke
};
const borrow = (port) => (...args) => port.postMessage(args);

In practice

// photo site lending a progress-bar callback to an embedded resizing tool
const onProgress = (done, total) => { bar.max = total; bar.value = done; };
const grant = lend(onProgress);
tool.contentWindow.postMessage({ resize: photos }, toolOrigin, [grant.port]);

// inside the resizing iframe
addEventListener("message", async (event) => {
  if (event.origin !== photoSiteOrigin) return;
  const onProgress = borrow(event.ports[0]);
  let done = 0;
  for (const photo of event.data.resize) {
    await shrink(photo);
    onProgress(++done, event.data.resize.length);  // executes in the host page
  }
});

// user dismisses the progress UI: revoke the callback port
dismissButton.onclick = () => grant.revoke();

How it works

You can't structured-clone or transfer a JavaScript function, but you can transfer a MessagePort. Keep the function on your side, wrap it in a channel that invokes it when arguments arrive, and transfer the other end. Need return values or thrown errors? Pair each call with a reply port — that's essentially Comlink in a nutshell.

The function never leaves your context, so it keeps its closure and origin privileges while the receiver can only invoke it, never inspect its source.

Closing your end revokes the callback cleanly from the receiver.

Step by step

What each press of Next does in the demo above.

  1. Lend onTick(). Wraps onTick() in a channel and transfers the callable port handle to the other origin.
  2. Start the countdown. The other origin invokes onTick() on each tick; every call executes back on this page.
  3. Take the function back. This page closes its end of the port, immediately revoking the callback.

What you can build with it

Built and running below.

An event listener that lives on another origin

Cross-origin callbacks and event listeners.

addEventListener takes a function, and a function cannot cross origins. A port can. This page listens to its own button and posts each press down a port. The analytics frame on another origin counts presses of a button it cannot see, in a page it cannot read. Close the port and it is unsubscribed.

Code

// the other origin wants: button.addEventListener("click", theirFunction)
const { port1, port2 } = new MessageChannel();
button.addEventListener("click", () => port1.postMessage({ type: "click", at: Date.now() }));
analytics.postMessage({ cmd: "listen" }, analyticsOrigin, [port2]);
// unsubscribe them
port1.close();

Step by step

What each press of Next does in this demo.

  1. Let analytics listen. A port goes to the analytics frame. Presses of this page's button will be posted down it.
  2. Press the page's button. The press is heard on the other origin.
  3. Press the page's button. And again.
  4. Unsubscribe analytics. This page closes the port.
  5. Press the page's button. The button still works here. The other origin hears nothing.

Lend one method of an object, and not the object

Exposing one specific method instead of an entire object.

This page has a cart with three methods: add, clear and total. A badge from another origin needs the total. It is given a port that calls cart.total() and nothing else. The badge can ask for the total as often as it likes. It cannot add, and it cannot clear, because the port it holds doesn't offer those methods.

Code

const cart = { items: [], add(item) {…}, clear() {…}, total() {…} };
const { port1, port2 } = new MessageChannel();
port1.onmessage = ({ data }) =>
  port1.postMessage(data.call === "total" ? { result: cart.total() } : { error: "not on this port" });
badge.postMessage({ cmd: "port" }, badgeOrigin, [port2]);

Step by step

What each press of Next does in this demo.

  1. Lend the badge cart.total. The badge gets a port that reaches one method.
  2. Add tulips to the cart. This page uses its own cart, with all its methods.
  3. Badge: ask for the total. The badge calls total through its port.
  4. Badge: try to clear the cart. The badge asks for a method it was not lent.

Call another origin's object as if it were local, in about twenty lines

RPC proxy libraries like Comlink and Hawser.

Libraries such as Comlink turn a port into something you call like an ordinary object. This is that idea at its smallest. On this page, wrap(port) returns a Proxy. Reading a property extends a path, and calling it posts the path and the arguments down the port and returns a promise. In the frame, expose(api, port) walks the path, calls the function, and posts back the result or the error. The walk only follows properties the object itself has. Without that check, a caller could ask for constructor and reach Function, which the Comlink page shows happening in Comlink 4.4.2.

Code

// this page
function wrap(port) {
  let last = 0; const waiting = new Map();
  port.onmessage = ({ data }) => {
    const pending = waiting.get(data.id); if (!pending) return; waiting.delete(data.id);
    "error" in data ? pending.reject(new Error(data.error)) : pending.resolve(data.result);
  };
  const at = (path) => new Proxy(() => {}, {
    get: (_, key) => key === "then" ? undefined : at([...path, key]),
    apply: (_, __, args) => new Promise((resolve, reject) => {
      waiting.set(++last, { resolve, reject });
      port.postMessage({ id: last, path, args });
    }),
  });
  return at([]);
}
const shop = wrap(port);
await shop.basket.total();

// the frame on another origin
function expose(api, port) {
  port.onmessage = async ({ data: { id, path, args } }) => {
    try {
      let owner = null, target = api;
      for (const key of path) {
        if (!Object.hasOwn(target, key)) throw new Error("nothing called " + path.join("."));
        owner = target; target = target[key];
      }
      port.postMessage({ id, result: await target.apply(owner, args) });
    } catch (err) { port.postMessage({ id, error: err.message }); }
  };
}

Step by step

What each press of Next does in this demo.

  1. Wrap the port. The frame exposes an object on its end. This page wraps the other end in a Proxy.
  2. shop.add(2, 3). A call that looks local. The path and the arguments went down the port, and 5 came back.
  3. shop.basket.add("lilies"). A method two levels down. It changes the basket that lives in the frame.
  4. shop.basket.total(). The total is worked out in the frame, from the basket as it is now.
  5. shop.reserve(). This method throws in the frame. The promise on this page rejects with the same message.
  6. shop.constructor("return 1"). The object has no property of its own called constructor, so the frame refuses.

Things to try

  • Lend onTick(), start the countdown, and watch each tick call arrive across the wire.
  • Click Take the function back mid-countdown and watch calls stop arriving immediately.

Gotchas

  • Every remote call is asynchronous even if the underlying function is synchronous.
  • The minimal 6-line wrapper is fire-and-forget; add a reply port or call ID map for return values and errors.
  • Arguments are structured-cloned snapshots, not live references.
  • Ports aren't garbage-collected automatically when a caller stops using a remote proxy — close proxies you're done with (or use Symbol.dispose).

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
<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
Proxy
An object that stands in for another and intercepts what is done to it, such as reading a property or calling it. MDNECMAScript
Symbol.dispose
The method the using keyword calls to clean up an object when it goes out of scope. MDN

Projects and documents this page draws on.

  • Comlink, by Surma and the Chrome Labs team.

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