How to communicate between iframe and the parent site? How to communicate between iframe and the parent site? ajax ajax

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', '*')


In 2018 and modern browsers you can send a custom event from iframe to parent window.

iframe:

var data = { foo: 'bar' }var event = new CustomEvent('myCustomEvent', { detail: data })window.parent.document.dispatchEvent(event)

parent:

window.document.addEventListener('myCustomEvent', handleEvent, false)function handleEvent(e) {  console.log(e.detail) // outputs: {foo: 'bar'}}

PS: Of course, you can send events in opposite direction same way.

document.querySelector('#iframe_id').contentDocument.dispatchEvent(event)


This library supports HTML5 postMessage and legacy browsers with resize+hash https://github.com/ternarylabs/porthole

Edit: Now in 2014, IE6/7 usage is quite low, IE8 and above all support postMessage so I now suggest to just use that.

https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage