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"></src>
<!-- ... -->
// Get the <iframe>'s window
var frameWindow = document.getElementById('frame-id').contentWindow;

// Add a listener for a response
window.addEventListener('message', function(evt) {
    
    // IMPORTANT: Check the origin of the data! 
    if (event.origin.indexOf('http://other-site.com') == 0) {
        
        // Check the response
        console.log(evt.data);
        /* ... */
    }
});        

// Send a message to the frame's window
frameWindow.postMessage(/* any obj or var */, '*');
window.addEventListener('message', function(evt) { 

    // IMPORTANT: Check the origin of the data! 
    if (event.origin.indexOf('http://main-site.com') == 0) {
        
        // Read and elaborate the received data
        console.log(evt.data);
        /* ... */

        // Send a response back to the main window
        window.parent.postMessage(/* any obj or var */, '*');
    }
});

Feedback about page:

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



Table Of Contents