Search code examples
iframeinternet-explorer-8postmessage

Does IE8 have any specific restrictions on postMessage to IFrames?


I have a web application with an iframe that needs to communicate with its hosting page. The iframe and the host are on different domains and protocols (the iframe is https, the main page http). I use postMessage to get a small bit of state (user tracking) from the outer page into the iframe.

When the iframe is loaded, it sends a short message out to the top page to ask for the visitorid:

if ($.w.top != $.w) $.f.postMessage($.w.top, 'Get visitorId');

($.f.postMessage(w, m) is just a wrapper around postMessage, that does nothing if typeof w.postMessage === 'undefined'). On the outer page, we have a message listener:

// Set up event listener so that we can respond when any iframes
// inside of us ask for our visitorId
$.f.listen($.w, 'message', giveVisitorId);
function giveVisitorId(event) {
  $.w['zzzzz'] = event.source;
  if (event.data === 'Get visitorId') {
    alert('about to reply from '+window.location.href+' with visitorid, typeof event.source.postMessage is ' + typeof(event.source.postMessage));
    event.source.postMessage('visitorId=' + $.v.visitorId, '*');
  }
}

The inner frame has a listener registered for the response:

$.f.listen($.w, 'message', receiveVisitorId);

function receiveVisitorId(event) {
  alert('receiveVisitorId called with: ' + event.data + ' in window '+window.location.href);
  var s = event.data.split('=');
  if (s[0] === 'visitorId' && s.length === 2) {
    $.v.visitorId = s[1];
    $.w.clearTimeout(giveUp);
    rest();
  }
}

This all works as it is supposed to on chrome and firefox on OSX (when the iframe is loaded we get two alerts, one from receiveVisitorId and one from giveVisitorId); however on IE8 on XP we only get the first alert (from giveVisitorId).

This is strange enough, since it seems that the postMessage going out works and the one going in doesn't; what's truly perplexing is that if we go to the console and run zzzzz.postMessage('hi', '*') the alert in receiveVisitorId happens just as expected! (Note that we saved event.source in window.zzzzz).

Does anyone have an idea why this might be happening?

PS: The definitions of $.w.listen and $.w.postMessage, for reference:

listen: function (el, ev, fn) {
  if (typeof $.w.addEventListener !== 'undefined') {
    el.addEventListener(ev, fn, false);
  }
  else if (typeof $.w.attachEvent !== 'undefined') {
    el.attachEvent('on' + ev, fn);
  }
},
postMessage: function(w, m) {
  if (typeof w.postMessage !== 'undefined') {
    w.postMessage(m, "*");
  }
},

Solution

  • We resolved it. The problem was that we were calling $.f.listen after $.f.postMessage in the inner iframe; so when the outer window posted a message to the inner, the listener had not yet been attached. I don't know why this happened in IE and not chrome or firefox, but we just put it down to timing differences between the browsers.