Communication between iframe and parent window [JavaScript]

In the iframe you’ll use the below code:

window.parent.postMessage("Hello World !", "http://your.site.web");

And in the parent window:

// function that will be called when the message is received
function receiveMessage(event) {
  alert(event.data); // it'll show "Hello World !"
}
// we listen to a message
if (window.addEventListener) {
  window.addEventListener('message', receiveMessage, false);
} else if (window.attachEvent) { // IE8
  window.attachEvent('onmessage', receiveMessage);
}

It’s working from IE8+, and all modern browsers, but make sure you have a HTML5 doctype (<!DOCTYPE html>)

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*