How to communicate between iframe and the parent site?

Danny Fox picture Danny Fox · Feb 5, 2012 · Viewed 152.9k times · Source

The website in the iframe isn't located in the same domain, but both are mine, and I would like to communicate between the iframe and the parent site. Is it possible?

Answer

user123444555621 picture user123444555621 · Feb 6, 2012

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.

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!');
    }
};

If you are posting message from iframe to parent window

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