postMessage

The postMessage method sends data from one window to another, also when the two have different origins. It is the safe way for a parent page and its iframe to talk.

Browser API

Also called window.postMessage

Updated

On this page

How it works

The sender calls postMessage(message, targetOrigin) on the window it wants to reach. The browser copies the message with the structured clone algorithm. It then fires a message event on the other window. If the origin of that window does not match targetOrigin, the browser drops the message with no error.

The receiver reads event.data, event.origin, and event.source. event.origin is the origin of the sender when it sent the message. event.source is the sender window, so the receiver can reply to it.

Security

Any window can send a message to your page. Check event.origin with an exact string before you use the data. Then check the shape of event.data, and never pass it to innerHTML or eval().

Name an exact target origin when you send data. The value "*" sends to any origin. The value "/" sends only to your own origin. If you do not expect messages from other sites, do not add a message listener.

Example

JavaScript
const frame = document.querySelector("iframe");

frame.contentWindow.postMessage(
  { type: "theme", value: "dark" },
  "https://widget.example"
);

The second argument is the target origin. The browser drops the message if the frame shows a page from another origin.

How to use it

Send with postMessage and an exact target origin. Receive with a message listener that checks event.origin first.

// On https://example.com
const frame = document.querySelector("iframe");
window.addEventListener("message", (event) => {
  if (event.origin !== "https://widget.example") return;
  if (event.data?.type === "ready") {
    frame.contentWindow.postMessage({ type: "init" }, "https://widget.example");
  }
});

Use "*" as the target origin only for data that any site may see. Never send tokens or user data with "*".

Learn more

Sources

Know before you embed.

Free, no sign-up, nothing stored. Paste a URL and get a verdict, a live preview, and the fix.