Communication between iFrames with IE8 support

Apr 17, 2014 • val antonini

This is a way to talk between iframes (even on different domains) with support for Internet Explorer 8 and 9 (which only support sending strings as the message data). It works by stringifying a JSON object and using that as the event data. It requires a jQuery 1.x to guarantee compatibility with IE8.

An example of it can be found here.

Place this in the outer iframe to listen for messages:

$(document).ready(function () {
    $(window).bind('message', function (event) {
        var x = JSON.parse(event.originalEvent.data);
        alert("outer iframe received: " + x.MyProperty);
    });
});

And post to the outer iframe from the inner iframe like this:

//replace with your desired JSON object
var sampleJsonObject = {
    MyProperty: "Inner Iframe Value"
};

parent.postMessage(
    JSON.stringify(sampleJsonObject),
    "http://arakawa.asia"
);

For posting to the inner iframe add the message binding code above to the inner iframe and post to the inner iframe (with an id of "innerIframe") from the outer iframe using the below:

//replace with your desired JSON object
var sampleJsonObject = {
    MyProperty: "Outer Iframe Value"
};

var iFrameContentWindow = $("#innerIframe")[0].contentWindow;
iFrameContentWindow.postMessage(
    JSON.stringify(sampleJsonObject),
    "http://arakawa.asia"
);

If you are doing this from razor you can use the below for the source url:

@String.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Host)//eg. resolves to http://localhost or http://url.com

e.g:

parent.postMessage(
    JSON.stringify(sampleJsonObject),
    "@String.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Host)"
);