public
Created

Backwards compatible window.postMessage()

  • Download Gist
XD.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
// from http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage/
 
var XD = function(){
var interval_id,
last_hash,
cache_bust = 1,
attached_callback,
window = this;
return {
postMessage: function(message, target_url, target){
if (!target_url) return;
target = target || parent; // default to parent
if (window['postMessage']){
// the browser supports window.postMessage, so call it with a targetOrigin
// set appropriately, based on the target_url parameter.
target['postMessage'](message, target_url.replace(/([^:]+:\/\/[^\/]+).*/, '$1'));
} else if (target_url){
// the browser does not support window.postMessage, so use the window.location.hash fragment hack
target.location = target_url.replace(/#.*$/, '') + '#' + (+new Date) + (cache_bust++) + '&' + message;
}
},
receiveMessage: function(callback, source_origin){
// browser supports window.postMessage
if (window['postMessage']){
// bind the callback to the actual event associated with window.postMessage
if (callback){
attached_callback = function(e){
if ((typeof source_origin === 'string' && e.origin !== source_origin)
|| (Object.prototype.toString.call(source_origin) === "[object Function]" && source_origin(e.origin) === !1)) {
return false;
}
callback(e);
};
}
if (window['addEventListener']){
window[callback ? 'addEventListener' : 'removeEventListener']('message', attached_callback, false);
} else {
window[callback ? 'attachEvent' : 'detachEvent']('onmessage', attached_callback);
}
} else {
// a polling loop is started & callback is called whenever the location.hash changes
interval_id && clearInterval(interval_id);
interval_id = null;
if (callback){
interval_id = setInterval(function(){
var hash = document.location.hash,
re = /^#?\d+&/;
if (hash !== last_hash && re.test(hash)){
last_hash = hash;
callback({data: hash.replace(re, '')});
}
}, 100);
}
}
}
};
}();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.