Testing the Cross Document Messaging

To test the cross document messaging, I'm including two nested <iframe>s. The first one called the Red frame contains the second one. To test the way the messages get passed, click one of the buttons. If cross-document messaging is working, the red frame will receive the message, change the second frame to point to the URL suggested in the message and then respond with a thankyou note. It's all so polite.




Response:


Here's the code for the Red Frame


<script type="text/javascript">
window.addEventListener('message', receiver, false);
function receiver(e) {
      document.getElementById("url").innerHTML="URL:"+e.data;
      document.getElementById("poster").src=e.data;
      e.source.postMessage('Thanks for telling me about '+e.data, e.origin);
}

</script>

<div style="color:#ff0000;"><h2> This is the Red Frame</h2></div>
<div style="font-family:Monospace" id="url"> URL: </div>

<iframe id="poster" src="">

</iframe>

Here's the code used in this posting



<script type="text/javascript">
function call(msg){
  var o = document.getElementsByTagName('iframe')[0];
  o.contentWindow.postMessage(msg, 'http://www.wayner.org/temp/temp2.html');
}
window.addEventListener('message', receiver, false);
function receiver(e) {
      document.getElementById("response").innerHTML="Response:"+e.data;
}
</script>
<input type="button" onclick="call('http://www.infoworld.com');" value="Load InfoWorld.com">
<input type="button" onclick="call('http://www.computerworld.com');" value="Load ComputerWorld.com">
<input type="button" onclick="call('http://www.pcworld.com');" value="Load pcworld.com">
<div style="font-family:Monospace" id="response"> Response: </div>


<iframe id="redframe" src="http://www.wayner.org/temp/temp2.html" width="100%" height="150px">


</iframe>