259

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?

7 Answers 7

461

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', '*')
12
  • 2
    thank you, but unfortunately it doesn't works in older browsers.
    – Danny Fox
    Feb 6, 2012 at 13:25
  • 116
    In the parent: window.onmesage = function().... In the iframe: window.top.postMessage('hello', '*') Aug 21, 2012 at 11:51
  • 5
    It's not a bug. File urls can be very unsafe and browsers are treating them with ever increasing care. Back in the old days you could put a link to file://C:/Windows/system32/whatever on a webpage and make it point right into the user's system folder. These days browsers mostly ignore clicks on links like that. Run a webserver and access your code through that and you'll see the errors diappear. Mar 27, 2014 at 20:46
  • 7
    As a good practice, never use the '*' for your target. In fact, MDN says - "Always provide a specific targetOrigin, not *, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site."
    – rodiwa
    Oct 29, 2015 at 8:14
  • 3
    We can even use window.frames[index] to get child frame (<iframe>, <object>, <frame>), equivalent to getElementsByTagName("iframe")[index].contentWindow. To get Parent Window Object from IFrames, it is better to use window.parent, as window.top represents the Top Most Parent Window
    – phoenisx
    Oct 8, 2017 at 5:34
98

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)
10
  • 3
    Hello, do I have to be on the same domain to do it ? Dec 13, 2018 at 13:07
  • 3
  • 1
    It should be noted that dispatchEvent is supported in all major browsers. IE9 was the first version it came in, so most OSs now work with it. caniuse.com/#search=dispatchEvent Aug 16, 2019 at 12:48
  • 3
    I am not able to communicate from parent to iframe with this method.
    – Avan
    Sep 27, 2019 at 8:44
  • 1
    There is a simple solution to that Avan and @radtek. All you have to do is first dispatch an event from the iframe to the parent that notifies the parent that the iframe is loaded (essentially a "ready message"). The parent will be listening for messages and if it receives the "ready message" event, it can then reply to the iframe with whatever message you want to send. That way it sends the message to the iframe only once the iframe is loaded. And of course the iframe page will only send the message to the parent once it is loaded.
    – Cannicide
    Jun 1, 2020 at 15:11
15

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

2
  • With the caveat that IE8/9 only support strings caniuse.com/#search=postmessage (See known issues)
    – Harry
    Nov 16, 2016 at 14:28
  • this can be worked around by encoding your event objects to json and decode them on the other side. May 11, 2017 at 8:50
12

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

From Iframe

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

Then from parent say back.

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

Updated:

postMessage should not work on cross domain, so the solution like this:

For example your website is: customer.com and your domain is my.com

You need to do like this

  • Create a js file (upload to CDN or your server) - my.com
  • Embed js file above to customer.com

Now from my.com, you can postMessage and above embed script can be received data from you.

4
  • 4
    As of this writing, March of 2021, cross-browser support for window.onmessage is not complete: developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/…
    – flyingace
    Mar 2, 2021 at 22:24
  • 1
    @flyingace The only caveat I'm aware of is cross-domain iframe messaging on IE. Are you aware of any gaps between modern browsers?
    – kevlened
    Oct 20, 2021 at 18:39
  • For cross-browser or crossing domain, you can embed a script with the same domain to website and postMessage it as normal. Cross domain will not work. So embed script is a solution, not a workaround.
    – Binh Ho
    Feb 13 at 14:06
  • 1
    THANKYOU!! lost so much hair over this. The only solution that actually worked
    – Sharkfin
    Mar 11 at 14:28
2

the window.top property should be able to give what you need.

E.g.

alert(top.location.href)

See http://cross-browser.com/talk/inter-frame_comm.html

1
  • 12
    As the iframe isn't on the same domain he can't access its parent. Feb 6, 2012 at 7:30
1

After spending 2 days trying to get an iFrame posting messages back to the parent, a Vue application in my situation, I came across this excellent reference:

https://dev-bay.com/iframe-and-parent-window-postmessage-communication/

From the iframe to parent:

    const parentWindow = window.parent;
    class Message {
        constructor(type, body) {
          this.type = type;
          this.body = body;
        }
    };

    function sendMessage (windowObj, payload) {
        if(windowObj) {
          windowObj.postMessage(payload, "*");
        }
    };

    //Then call appropriately: 
    sendMessage(parentWindow, new Message("button-click", "Show Stats Overlay"));

In the parent, my Vue application mounted life cycle event, but reference the link for your own requirement:

    window.addEventListener("message", (e) => {
        var data = e.data;
        console.log("RECEIVED message from CHILD TO PARENT", data);
        
        var type = data.type;
        var body = data.body;

        if(type === "button-click" && body) {
          console.log("button-click RECEIVED FROM CHILD")
          //Additional functionality ...
        } else if (type === "text-msg" && body) {
          console.log("TEXT MESSAGE RECEIVED FROM CHILD");
          //Additional functionality ...
        }
      });

Please see reference for examples of communication from Parent to iFrame.

Hope this helps someone else.

0

You can also use

postMessage(message, '*');

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.