2009年3月21日星期六

HTML5 Cross Document Messaging

Monday, November 17, 2008
HTML5 Cross Document Messaging

So I got to play with HTML5 Cross Document Messaging this weekend and built this quick demo -

[ demo ] [ source code ]

The demo demonstrates how easy it is for two iframe of different origins to talk to each other. In real time, each iframe is passing its own mouse coordinates from "onmousemove" event to each other.Right now, this feature is only supported in Firefox 3, IE8, Opera 9 and Safari Nightlies.

The basic semantic is to use postMessage() to send data to a window object and the receiving window should register for the "onmessage" event to receive data.
view plaincopy to clipboardprint?
window.document.onmousemove = function(e) {
var x = (window.Event) ? e.pageX : window.event.clientX;
var y = (window.Event) ? e.pageY : window.event.clientY;

// this send data to the second iframe of the current page
window.parent.frames[1].postMessage('x = ' + x + ' y = ' + y, '*');
};

var onmessage = function(e) {
var data = e.data;
var origin = e.origin;
document.getElementById('display').innerHTML = data;
};

if (typeof window.addEventListener != 'undefined') {
window.addEventListener('message', onmessage, false);
} else if (typeof window.attachEvent != 'undefined') {
window.attachEvent('onmessage', onmessage);
}

window.document.onmousemove = function(e) {
var x = (window.Event) ? e.pageX : window.event.clientX;
var y = (window.Event) ? e.pageY : window.event.clientY;

// this send data to the second iframe of the current page
window.parent.frames[1].postMessage('x = ' + x + ' y = ' + y, '*');
};

var onmessage = function(e) {
var data = e.data;
var origin = e.origin;
document.getElementById('display').innerHTML = data;
};

if (typeof window.addEventListener != 'undefined') {
window.addEventListener('message', onmessage, false);
} else if (typeof window.attachEvent != 'undefined') {
window.attachEvent('onmessage', onmessage);
}
One thing to beware of is that for some reason it would not receive data properly if you use the traditional event listener setup for "onmessage" event. You have to use addEventListener() -
view plaincopy to clipboardprint?
window.onmessage = function() {
// did not work in FF3
};

window.onmessage = function() {
// did not work in FF3
};
This is a really neat feature and I can see it being extremely useful for platform builder or widget container to share common data easily and efficiently.
Posted by austinchau at 10:47 AM
Labels: Cross Document Messaging, HTML5, javascript

没有评论:

发表评论