Monday, May 10, 2010

HTML 5 postMessage (Cross-Domain Message) on Firefox 3.6.3

This only works in Firefox because IE uses attachEvent(). You can always use dojo.connect( window, 'message', func() ) so it works in Firefox and IE.

A (http://localhost/cross.htm) has an iframe containing B (http://otherdomain/cross.htm)

After the iframe is loaded in A, then a message is sent to it (containing string 'Hello'). The origin is checked in B, and if it matches an alert is displayed.

on A (http://localhost/cross.htm)
<script type="text/javascript">
function iframeload() {
var o = document.getElementById('crossid').contentWindow;
o.postMessage('Hello', "http://otherdomain/cross.htm");
}
</script>

<iframe id="crossid" onload="iframeload();" src="http://otherdomain/cross.htm" width="700px" height="700px">
</iframe>


on B (http://otherdomain/cross.htm)
window.addEventListener('message',function(e) {
if (e.origin == 'http://localhost') {
if (e.data == 'Hello') {
alert(e.data);
e.source.postMessage('Hello');
} else {
alert(e.data);
}
}
}, false);

No comments:

Post a Comment