Skip to content
Tutorials Center
My learning

Topics

Lesson 97 of 122 ยท Web APIs

Cross-Document Messaging with postMessage

Send data between a page and its iframes or popups with window.postMessage. Learn targetOrigin, event.origin checks, structured cloning and MessageChannel.

A page often shares the screen with documents it does not control: a payment form in an iframe, a video player from another site, a chat widget, or a popup that handles a sign-in. The browser keeps these documents apart on purpose. A script on one origin cannot read the DOM, cookies or variables of a document on another origin.

Sometimes, though, the two sides want to talk. The payment frame needs to say "paid", and the page needs to tell the video player "pause". The safe, official way to do that is cross-document messaging with window.postMessage(). Each side sends plain data, the other side decides whether to trust it, and nobody reaches into anybody else's page.

In this lesson you will send messages in both directions between a page and an iframe, check where messages come from, learn which values can travel, and open a private channel with MessageChannel.

Why windows cannot just talk

Every document has an origin: the scheme, host and port of its URL. https://shop.example and https://shop.example:443 are the same origin; https://pay.example, http://shop.example and https://api.shop.example are all different ones.

The browser's same-origin policy says a script may only touch documents of its own origin. If your page embeds https://maps.example in an iframe, frame.contentWindow.document throws a SecurityError. That rule is what stops a random site from framing your bank and reading your balance. The next lesson, Cross-Origin Requests and CORS, shows how the same policy applies to network requests.

postMessage() is a deliberate, narrow hole in that wall. You cannot read the other document, but you can hand it a message, and it can hand you one back.

Sending a message

You call postMessage() on the window you want to reach, not on your own window. So the first job is to get a reference to the other window:

You areโ€ฆ The other window isโ€ฆ
A page with an iframe iframe.contentWindow
A document inside an iframe window.parent (or window.top for the outermost page)
A page that opened a popup the value returned by window.open()
A popup window.opener (null if the link used noopener)

Then send data plus a target origin:

JavaScript
const frame = document.querySelector("#checkout");

frame.contentWindow.postMessage(
  { type: "set-total", amount: 42.5, currency: "EUR" },
  "https://pay.example"   // only deliver if the frame is still on this origin
);

The second argument protects your data. The browser checks the origin of the receiving window at the moment of delivery. If the iframe has navigated somewhere else, for example because an attacker redirected it, the message is silently dropped. You have three choices:

  • An exact origin such as "https://pay.example": the safe default for anything that matters.
  • "/": deliver only to a window with the same origin as the sender.
  • "*": deliver to whatever is there. Use it only for data that is harmless if a stranger reads it.

There is also an options form that does the same thing: win.postMessage(data, { targetOrigin: "https://pay.example" }).

postMessage() returns immediately. The message is queued and delivered as a task, a moment later, so the code after the call always runs first.

Receiving a message

The receiving window listens for the message event:

JavaScript
window.addEventListener("message", (event) => {
  if (event.origin !== "https://shop.example") {
    return; // not from a site we trust: ignore it
  }

  console.log(event.data);   // the data that was sent (a copy)
  console.log(event.source); // the window that sent it, so you can reply
});

The event carries four useful properties:

  • event.data: a copy of whatever was sent.
  • event.origin: the sender's origin as a string, such as "https://shop.example". The browser fills this in, so the sender cannot fake it.
  • event.source: the sender's window. Call event.source.postMessage(...) to answer.
  • event.ports: any MessagePort objects transferred with the message (more on these below).

Here is a complete round trip. The page builds an iframe from a <template>, and both sides send and receive.

A page and an iframe talking

A few details are worth noticing:

  • Messages are objects with a type. That small convention makes it easy to handle several kinds of message in one listener and to ignore anything unexpected.
  • The child sends a ready message as soon as its script runs. Messages sent to a frame before it has loaded its listener are simply lost, so a "ready" handshake is the reliable way to know when the other side is listening.
  • The child writes its output into its own page. The console panel below the preview only shows messages from the outer document.

Why the origin says "null" here

Look at the origin the child reports: null. The examples on this site run in a sandboxed iframe with an opaque origin, a unique origin that matches nothing, not even itself. The inner frame has sandbox="allow-scripts" too, so it gets its own opaque origin. An opaque origin is serialized as the string "null", and you cannot target it by name, which is why these demos send with "*" and identify the other side with event.source instead.

On a real site, both sides have proper origins like https://shop.example. There you should always pass an exact targetOrigin and check event.origin. Never treat "null" as a trusted origin: any sandboxed frame, data: URL or local file can produce it.

Checking where a message came from

Any window that has a reference to yours can send you a message: a frame you embedded, a popup you opened, or a malicious page that opened your page with window.open(). Your listener is a public door, so the very first thing it does is check who is knocking.

The rules are short:

  1. Compare event.origin with an exact string, or look it up in a Set of allowed origins.
  2. Validate the shape of event.data before using it: check the type, check that numbers are numbers, and ignore anything else.
  3. Treat the data as untrusted text. Never pass it to innerHTML, eval() or a URL you navigate to without checking it. Use textContent, as you learned in The Document Object Model.

Loose string checks are the classic mistake. Run this and see which checks a hostile origin can fool:

Which origin checks are safe?

Only exact and allowlist behave correctly. startsWith accepts https://shop.example.attacker.test, a domain the attacker can register. includes also accepts https://myshop.example. The regular expression has no ^ and $ anchors, and its unescaped . matches any character, so it lets through two impostors. If you really need a pattern, anchor it and escape the dots: /^https:\/\/shop\.example$/.

Check event.origin, not event.data. A message that says { from: "shop.example" } proves nothing, because the sender writes the data. Only event.origin is set by the browser. And when you send something private, such as a token, always use an exact targetOrigin, never "*".

What you can send

postMessage() does not send a reference to your object. It makes a copy using the structured clone algorithm, the same one behind structuredClone(), Web Workers and IndexedDB. The receiver gets an independent copy, so changing it never affects the original.

Structured cloning handles far more than JSON:

  • Primitives, plain objects and arrays, including nested and circular ones.
  • Date, RegExp, Map, Set, ArrayBuffer, typed arrays, Blob, File and ImageData.
  • Error objects (most built-in error types).

Some things cannot be cloned. Functions, DOM nodes and symbols throw a DataCloneError. Class instances lose their class and arrive as plain objects, and getters are turned into ordinary values.

Transferring instead of copying

Copying a large binary buffer takes time and memory. Instead you can transfer it: ownership moves to the receiver and the sender's copy becomes empty (its byteLength drops to 0). Pass transferable objects in the third argument, or as transfer in the options form:

JavaScript
const pixels = new ArrayBuffer(8_000_000);
frame.contentWindow.postMessage({ type: "image", pixels }, "https://editor.example", [pixels]);
console.log(pixels.byteLength); // 0: the buffer now belongs to the frame

structuredClone() uses the same rules, so you can explore them without any second window:

What survives structured cloning?

The Point copy keeps x and y but loses its class and the length getter. If the receiver needs behavior, send plain data and rebuild the object on the other side.

Private channels with MessageChannel

Window messages all arrive at one message listener, mixed together with messages from every other frame, extension and script. For a long conversation between two parties, a MessageChannel is cleaner. It creates a pair of connected ports: whatever you post into port1 comes out of port2, and the other way around.

The usual pattern:

  1. The page creates a channel and keeps port1.
  2. It sends port2 to the frame once, using postMessage() with port2 in the transfer list, and an origin check like any other message.
  3. From then on, both sides talk over their ports. No one else holds a port, so no one else can join the conversation, and no origin check is needed per message.

Each port has its own onmessage handler and its own postMessage(data), with no target origin, because a port only has one other end.

Talking over a MessageChannel

This time the parent waits for the iframe's load event before sending the port. That works too, because by the time load fires the frame's script has run and its listener exists. Notice that the frame's port listener never checks an origin: only the parent could have handed it that port.

A port uses onmessage here. If you use addEventListener("message", โ€ฆ) on a port instead, you must also call port.start(), or no messages arrive.

Where else you will meet postMessage

The same messaging model shows up across the platform, so learning it once pays off several times:

  • Web Workers use worker.postMessage() and a message event, with the same structured cloning and transfer rules. See Web Workers.
  • BroadcastChannel sends a message to every tab, window and frame of the same origin that opened a channel with the same name: new BroadcastChannel("cart").postMessage({ items: 3 }). It is handy for "you logged out in another tab".
  • Service workers talk to their pages with postMessage() as well.
  • Popups opened with window.open() use exactly the window messaging you saw above, for example to send a sign-in result back to window.opener.

When choosing, use window postMessage() to talk across origins, BroadcastChannel for same-origin tabs, and MessageChannel when two parties need a private line.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Your page embeds a checkout iframe from https://pay.example. How should you send it the order total?

    You post to the other window (contentWindow) with an exact target origin. Reaching into a cross-origin document throws, and "*" would deliver the data to whatever page the frame happens to show.
  2. 2. Which listener check is safe if you only trust https://shop.example?

    Only an exact comparison works. The prefix and substring checks accept attacker domains like shop.example.attacker.test, and event.data is written by the sender, so it proves nothing.
  3. 3. What happens when you post an object that contains a function?

    Structured cloning cannot copy functions, DOM nodes or symbols, so postMessage() throws a DataCloneError.
  4. 4. What does transferring an ArrayBuffer in the third argument of postMessage() do?

    A transfer moves the buffer instead of copying it. Afterwards the sender's buffer is detached and its byteLength is 0.
  5. 5. Why would you use a MessageChannel instead of plain window messages?

    Once a port has been handed over, only the holder of the other port can talk on that line, so the conversation is kept apart from every other message.

Summary

  • The same-origin policy keeps documents of different origins apart; postMessage() is the sanctioned way to exchange data between them.
  • Call postMessage(data, targetOrigin) on the other window: iframe.contentWindow, window.parent, window.opener or a popup.
  • Use an exact targetOrigin for anything sensitive; "*" delivers to whoever is there.
  • In the message listener, check event.origin against an exact string or allowlist, validate event.data, and treat it as untrusted text.
  • Messages are structured clones: rich types survive, functions and DOM nodes throw, and buffers can be transferred.
  • A "ready" handshake (or the iframe's load event) avoids sending messages before the other side is listening.
  • MessageChannel gives two parties a private line; BroadcastChannel reaches same-origin tabs.

Next lesson: Cross-Origin Requests and CORS, where you see how the same-origin policy applies to fetch(), images and scripts, and how servers opt in to sharing.