JavaScriptMedium
How do <iframe on a page communicate?
By FrontendPro Editorial Team Updated 8/8/2026
#JavaScript
Answer
<iframe> elements on a page can communicate using the postMessage API. This allows for secure cross-origin communication between the parent page and the iframe. The postMessage method sends a message, and the message event listener receives it. Here's a simple example:
js
// In the parent page
const iframe = document.querySelector("iframe");
iframe.contentWindow.postMessage("Hello from parent", "*");
// In the iframe
window.addEventListener("message", (event) => {
console.log(event.data); // 'Hello from parent'
});
