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
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