postMessage API
window.postMessage() enables safe communication between a parent page and a cross-origin iframe. It is the only way to communicate across origins.
Always validate the origin of incoming messages before acting on the data.
window.postMessage() enables safe communication between a parent page and a cross-origin iframe. It is the only way to communicate across origins.
Always validate the origin of incoming messages before acting on the data.
// Parent page sends message to iframe
const iframe = document.querySelector("iframe");
iframe.contentWindow.postMessage({ action: "resize", height: 300 }, "https://widget.com");
// Inside the iframe — listen for messages
window.addEventListener("message", (event) => {
if (event.origin !== "https://parent.com") return; // Security check
console.log("Received:", event.data);
});
Always verify event.origin before processing postMessage data — malicious pages can send messages too.