[ 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.
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() -
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.