new MessageChannel() gives you two entangled ports. Keep one and transfer the other to any frame, window or worker you already have a handle to. After that you've got a private channel: scripts listening for window.postMessage events won't see a single message that goes down it.
When you'd use this
A shop embeds a third-party support chat iframe on its order page. Once the iframe loads, the shop creates a MessageChannel and posts one end in. The chat validates event.origin once when the port arrives and keeps the port. After that, order details flow down the private channel — analytics and third-party scripts listening to window message events never see a byte of it.
// inside an embedded support-chat iframe on a shop's order pageaddEventListener("message", (event) => {
// verify the origin once here — messages on the port need no origin checkif (event.origin !== shopOrigin || event.data !== "here") return;
const port = event.ports[0]; // port2 now belongs to the frame// any message posted before this ran queued inside the port
port.onmessage = (e) => {
if (e.data === "ping") port.postMessage("pong");
elseshowOrder(e.data.order);
};
});
// back in the shop's page when the user opens an order
port1.postMessage({ order: "A-1041" });
How it works
new MessageChannel() gives you two ports joined to each other and nothing else. Whatever goes into one comes out of the other in order. There's no origin check on every message because nobody else has access to the channel.
A port is one of the few web objects you can transfer with postMessage. Put it in the transfer list and it moves out of your context and into the receiver's, still entangled with its twin. Every pattern on this site builds on that one primitive.
Compare that with window.postMessage, where every listener on the window sees every message and you have to validate event.origin and event.source on every call. With a port, you check identity once when you hand the port over — after that, the port itself is the channel.
Step by step
What each press of Next does in the demo above.
Open a channel. Creates a MessageChannel and transfers port2 over to the frame, forming a private channel.
Send a ping. Sends ping 1 down port1 and receives pong 1 right back on the same channel.
What you can build with it
Built and running below.
A private line that other window message listeners do not hear
A private line between a host page and an embedded widget that third-party scripts listening to window message events can't eavesdrop on.
A sign-in widget from another origin has a token to hand to this page. If it posts the token to the window, every script listening on window hears it, including an advert's. If the page first gives the widget one end of a channel, the token arrives on that port alone rather than on the shared window bus (though a malicious script running in the same page could still tamper with globals before the port is created).
Code
// heard by every "message" listener in the pageparent.postMessage({ token }, parentOrigin);
// heard only by whoever holds the other end
port.postMessage({ token });
Step by step
What each press of Next does in this demo.
Widget: post the token to the window. The page gets the token. So does the advert's script, which only had to listen.
Open a private line. This page makes a channel, keeps one end and gives the widget the other.
Widget: post the token down the line. The token arrives on the page's port. The advert's script hears nothing.
One window.postMessage to deliver a port, and everything after it on the port
The bootstrap handshake for any protocol on this site: one window.postMessage to deliver a port, then ports only.
This page calls window.postMessage on the frame once. That message carries nothing except one end of a channel. Everything after it goes over the port: a question with an answer, then a subscription that sends five prices. The frame counts what it hears on its window and what it hears on the port, and sends both counts back with every reply. The window count stays at one however long the conversation goes on. The buttons below use the port only.
Code
const { port1, port2 } = newMessageChannel();
frame.contentWindow.postMessage({ cmd: "port" }, widgetOrigin, [port2]); // the only window message// from here on, only the port
port1.postMessage({ id: 1, sum: [19, 23] });
port1.postMessage({ subscribe: "prices" });
port1.onmessage = ({ data }) => show(data);
Step by step
What each press of Next does in this demo.
Deliver a port with one window.postMessage. The frame's window hears one message. It holds a port and no data.
Ask for a sum over the port. The question and the answer both travel on the port. The window count is still one.
Subscribe to prices over the port. Five prices arrive, half a second apart, all on the port.
Ask for a sum over the port. Still the same port, and the frame's window has still heard one message.
Things to try
Open the channel and watch the yellow port2 badge cross to the frame, then fire a few pings in a row.
Hit Start again and check the frame's log before opening the channel: no port has arrived yet.
Gotchas
If you attach a listener with addEventListener, the port stays silent until you call port.start(). Setting onmessage starts it automatically.
Messages posted before the other side starts listening queue inside the port instead of being dropped. You can transfer a port and start posting into it straight away.
Transferring a port neuters it in the sender — posting the same port a second time throws.
Never pass "*" as the target origin when delivering a port to an iframe; if the frame navigated elsewhere, the wrong site gets the port. Wait for a ready signal or verify the target origin first.
The web platform features this page mentions, with what each one is, its documentation on MDN and the specification that defines it.
MessageChannel
Makes a new pair of joined ports, port1 and port2. MDNHTML Standard
Window.postMessage()
Sends a message to another window or frame, which can be on a different origin. The receiver has to check who sent it. 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
Sends a message through a port. A second argument lists the objects to move instead of copy. MDNHTML Standard
Transferable objects
Objects that can be moved to another page or worker instead of copied. After the move the sender can no longer use them. The transfer list is the argument to postMessage that names them. MDNHTML Standard
MessageEvent.source
The window, port or worker that sent a message. MDNHTML Standard
MessagePort.start()
Starts delivery of the messages queued on a port. It is needed when you listen with addEventListener, and not when you set onmessage. MDNHTML Standard