SyntaxStudy
Sign Up
HTML Cross-Frame Communication with postMessage
HTML Advanced 6 min read

Cross-Frame Communication with postMessage

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.

Example
// 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);
});
Pro Tip

Always verify event.origin before processing postMessage data — malicious pages can send messages too.