Coder Perfect

What is the best way to communicate between an iframe and its parent site?


The iframe’s website isn’t on the same domain as the parent site, but they’re both mine, and I’d like to interact between the two. Is that even possible?

Asked by Danny Fox

Solution #1

It is not possible to call methods or access the iframe’s content document directly while using separate domains.

Cross-document messaging is required.

In the top window, for example:

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

as well as in the iframe:

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

In the top window, for example:

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

as well as in the iframe:'hello', '*')

Answered by user123444555621

Solution #2

You can send a custom event from an iframe to the parent window in 2018 and contemporary browsers.


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: You can, of course, send events in the reverse direction in the same way.


Answered by Stranger in the Q

Solution #3

This library works with HTML5 postMessage and resize+hash in legacy browsers

Edit: In 2014, IE6/7 usage is fairly low, and since IE8 and above all allow postMessage, I now recommend that you use that instead.

Answered by jpillora

Solution #4

To send a message back to the sender, use event.source.window.postMessage.

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

Then the parent responds.

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

Answered by Binh Ho

Solution #5

the view from the window A good property should be able to provide everything you require.




Answered by sambomartin

Post is based on