Home > Web Front-end > JS Tutorial > How to Enable Communication Between Browser Windows with JavaScript

How to Enable Communication Between Browser Windows with JavaScript

DDD
Release: 2024-11-20 13:27:15
Original
463 people have browsed it

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");

Copy after login

The above is the detailed content of How to Enable Communication Between Browser Windows with JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template