Wednesday, September 12, 2012

postMessage Sample Codes

Cross-document messaging has 2 parts: sender and receivers. Sender can be parent window or child window,  and reciever can be child window and parent window. (sibling windows should also work, for browser tab or windows, need further research.) Here we only talk about the main window includes one iframe case for cross-document (cross-domain) messaging.

Sender (main window):
    var win = document.getElementById("iframe").contentWindow;
    win.postMessage(
            'the-sample-message',
            "http://www.target-origin.com"
    );


Sender (iframe window):
    parent.postMessage(msg, 'http://www.target-origin');

Receiver (onmessage event):
    window.onmessage = function(e){
        if ( e.origin !== "http://www.origin.com" ) {
            return;
        }
        // parse and validate e.data

        // processing e.data
    };

Receiver (customized event handler):
     var handleMessage = function(e) {
         if ( e.origin !== "http://www.origin.com" ) {
            return;
         }     

        // parse and validate e.data
        // processing e.data
    };

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


References
http://www.w3.org/TR/webmessaging/#web-messaging
https://developer.mozilla.org/en-US/docs/DOM/window.postMessage
http://html5demos.com/postmessage2

addEvent utility function (from html5demos.com, good for reference)
var addEvent = (function () {
if (document.addEventListener) {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.addEventListener(type, fn, false);
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
} else {
return function (el, type, fn) {
if (el && el.nodeName || el === window) {
el.attachEvent('on' + type, function () { return fn.call(el, window.event); });
} else if (el && el.length) {
for (var i = 0; i < el.length; i++) {
addEvent(el[i], type, fn);
}
}
};
}
})();



No comments:

Post a Comment