How to communicate between iframe and the parent site?

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?

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 ( == 'hello') {
        alert('It works!');

If you are posting message from iframe to parent window'hello', '*')

It must be here, because accepted answer from 2012

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


var data = { foo: 'bar' }
var event = new CustomEvent('myCustomEvent', { detail: data })


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.


This library supports HTML5 postMessage and legacy browsers with resize+hash

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

the property should be able to give what you need.




You can also use

postMessage(message, '*');

Use event.source.window.postMessage to send back to sender.

From Iframe'I am Iframe', '*')
window.onmessage = (event) => {
    if ( === 'GOT_YOU_IFRAME') {
        console.log('Parent received successfully.')

Then from parent say back.

window.onmessage = (event) => {
    event.source.window.postMessage('GOT_YOU_IFRAME', '*')