DEV Community

Heru Hartanto
Heru Hartanto

Posted on

How to Enable Communication Between Browser Windows with JavaScript

The postMessage API in JavaScript is a powerful tool for securely enabling cross-origin communication between different windows or iframes. It’s commonly used to exchange data between a parent component and an embedded iframe, allowing for controlled interaction even if the documents originate from different sources.

Here’s a practical example of using postMessage to send data between an iframe and a parent component:


// Parent Component
const iframe = document.getElementById("myIframe");

// Send a message to the iframe
iframe.contentWindow.postMessage("Hello from parent", "https://iframe-domain.here");

// Listen the message
window.addEventListener("message", (event) => {
    if (event.origin === "https://iframe-domain.here") {
        console.log("Message from iframe:", event.data);
    }
}, false);


// Iframe Component
// Send a message to the parent
window.parent.postMessage("Hello from iframe", "https://parent-domain.here");

Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more