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.
Content of http://main-site.com/index.html
:
<!-- ... -->
<iframe id="frame-id" src="http://other-site.com/index.html"></iframe>
<script src="main_site_script.js"></script>
<!-- ... -->
Content of http://other-site.com/index.html
:
<!-- ... -->
<script src="other_site_script.js"></src>
<!-- ... -->
Content of main_site_script.js
:
// 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 */, '*');
Content of other_site_script.js
:
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 */, '*');
}
});