javascriptiframepostmessage

Javascript postMessage


How does a browser like chrome exchange data between a window and its IFrame (window being on 1 domain name and IFrame loads content from another domain name)?

My question is, how the browser can send a JS object to an IFrame? Is it done with HTTP request or some other network protocol?

I can't see it in Chrome's network tab, that's why I was wondering


Solution

  • TLDR; because the parent window can directly get the iframe's Window, the browser can use an offline, event-based communication protocol to communicate.

    A network protocol is not needed in this case as the parent window can directly reference the embedded iframe's Window object (using HTMLIFrameElement.contentWindow, which can then be used to listen to MessageEvents).

    When the parent window calls otherWindow.postMessage(...), that message is serialized internally and passed to the otherWindow, which automatically deserializes the object so long as the iframe's Window is listening for MessageEvents by having registered an event listener for message like so:

    window.addEventListener("message", function(event) {
        // passed offline using serialization algorithm specified in spec (2.9.1)
        console.log(event.data); // contains deserialized object
    });