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.
- Let analytics listen. A port goes to the analytics frame. Presses of this page's button will be posted down it.
- Press the page's button. The press is heard on the other origin.
- Press the page's button. And again.
- Unsubscribe analytics. This page closes the port.
- 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.
- Lend the badge cart.total. The badge gets a port that reaches one method.
- Add tulips to the cart. This page uses its own cart, with all its methods.
- Badge: ask for the total. The badge calls total through its port.
- 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.
- Wrap the port. The frame exposes an object on its end. This page wraps the other end in a Proxy.
- shop.add(2, 3). A call that looks local. The path and the arguments went down the port, and 5 came back.
- shop.basket.add("lilies"). A method two levels down. It changes the basket that lives in the frame.
- shop.basket.total(). The total is worked out in the frame, from the basket as it is now.
- shop.reserve(). This method throws in the frame. The promise on this page rejects with the same message.
- shop.constructor("return 1"). The object has no property of its own called constructor, so the frame refuses.