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:


Same origin policy, cross-origin communication:
* Safe cross-origin communication with messages

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
87 Same origin policy, cross-origin communication
89 WeakMap
90 WeakSet
102 Tilde