How to communicate between iframe and the parent site?

With different domains, it is not possible to call methods or access the iframe’s content document directly.

You have to use cross-document messaging.

parent -> iframe

For example in the top window:

myIframe.contentWindow.postMessage('hello', '*');

and in the iframe:

window.onmessage = function(e) {
    if (e.data == 'hello') {
        alert('It works!');
    }
};

iframe -> parent

For example in the top window:

window.onmessage = function(e) {
    if (e.data == 'hello') {
        alert('It works!');
    }
};

and in the iframe:

window.top.postMessage('hello', '*')

Leave a Comment