1

I've uploaded an HTML containing the following section:

<script>
window.onload = function(){
  window.addEventListener('message', receiver, false);
}

function receiver(event) {
  if (event.origin == 'http://documentA.com') {
    if (event.data == 'Hello B') {
      //event.source.postMessage('Hello A, how are you?', event.origin);
      alert("Recognized.");
    } else {
      //alert(event.data);
      alert("Unrecognized!");
    }
  }
}
</script>

The document is accessible and I can view it in the browser. Then, I open a console window using FireBug and type in the following call (as described at Wikipedia).

window.postMessage("12345", "http://server:port/Index4.htm");

As a result I get undefined and frankly I have no clue if it's a good thing or a bad thing. Probably bad, especially since I don't get to see any alerts. What to do?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • The result `undefined` just means, that `postMessage` does not return any value when you call it. It doesn't mean anything what can help you on debugging. – Nippey Nov 27 '12 at 09:19

1 Answers1

0

At first:

You have to post the message to the iframe. Try to use:

document.getElementById("yourIFrameID").contentWindow.postMessage()


I did the following in Opera Dragonfly, Firebug and IE9 and it works with no problems:

//Add iframe: <iframe id="teest" src="http://www.dict.cc/?s=annahme">
var frame = document.getElementById("teest")

Switch to iframe context:

//Add event listener
window.addEventListener("message", function(ev){ console.log(ev.data); }, false);

Back in the top-context, send some stuff:

frame.contentWindow.postMessage("foo", "http://www.dict.cc")
//Works. console: "foo"
frame.contentWindow.postMessage("foo", "http://www.dict.cc:80")
//Works. console: "foo"
frame.contentWindow.postMessage("foo", "http://www.dict.cc/?s=annahme")
//Works. console: "foo"
frame.contentWindow.postMessage("foo", "http://dict.cc/?s=annahme")
//Does NOT work. console: Nothing Happened

So, I see difficulties if you forget to add the right subdomain to the second parameter or if you visit a "https" page but have "http" in your string.
Try to remove all if's in your event handler and print out what you get before using if (or even better inspect it with Firebug or Dragonfly)

Nippey
  • 4,708
  • 36
  • 44
  • 1
    cross-document messaging in IE seams to work only in iframes. See [here](http://caniuse.com/#feat=x-doc-messaging) – AlexandruSerban Nov 27 '12 at 09:23
  • 1
    @nameIsNull The questioner is actually working with IE but tests stuff in FF because he's too lazy to look for plug-ins he already has for the latter. :) Also, I'd like to learn a way to handle my issue in a browser-independent way and I'm hugely confused, so **any** hint is a good hint at this point. –  Nov 27 '12 at 09:33