Safe cross-origin communication with messages

suggest change

The window.postMessage() method together with its relative event handler window.onmessage can be safely used to enable cross-origin communication.

The postMessage() method of the target window can be called to send a message to another window, which will be able to intercept it with its onmessage event handler, elaborate it, and, if necessary, send a response back to the sender window using postMessage() again.

Example of Window communicating with a children frame

<!-- ... -->
<iframe id="frame-id" src="http://other-site.com/index.html"></iframe>
<script src="main_site_script.js"></script>
<!-- ... -->
<!-- ... -->
<script src="other_site_script.js"></script>
<!-- ... -->
// Get the <iframe>'s window
var frameWindow = document.getElementById('frame-id').contentWindow;

// Add a listener for a response
window.addEventListener('message', function(evt) {
    // Compare the exact origin. A prefix check would allow other-site.com.evil.example.
    if (evt.origin === "http://other-site.com") {
        console.log(evt.data);
    }
});

// Send a message to the frame's window. "*" would accept any target origin.
frameWindow.postMessage({ type: "ping" }, "http://other-site.com");
window.addEventListener('message', function(evt) {
    if (evt.origin === "http://main-site.com") {
        console.log(evt.data);
        window.parent.postMessage({ type: "pong" }, "http://main-site.com");
    }
});

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents