Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created September 15, 2010 16:50
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cowboy/581030 to your computer and use it in GitHub Desktop.
Save cowboy/581030 to your computer and use it in GitHub Desktop.
postMessage detector
/*!
* postMessage detector - v0.1pre - 9/15/2010
* http://benalman.com/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// If `window.postMessage.complex` is true, postMessage can pass complex non-string
// values like objects and arrays. If it's false, it can only pass strings (TODO: test)
//
// Note that since postMessage executes asynchronously, this value isn't available
// immediately... Ugh.
(function(window,message,postMessage){
var tmp,
timeout_id = setTimeout(function(){
handler({});
},1);
function handler(e){
clearTimeout( timeout_id );
tmp = e.data;
if ( window.postMessage ) {
window.postMessage.complex = tmp && typeof tmp != 'string' && tmp.t;
}
if ( tmp = window.removeEventListener ) {
tmp( message, handler, false );
} else if ( tmp = window.detachEvent ) {
tmp( 'on' + message, handler );
}
};
if ( postMessage in window ) {
if ( tmp = window.addEventListener ) {
tmp( message, handler, false );
} else if ( tmp = window.attachEvent ) {
tmp( 'on' + message, handler );
}
window[ postMessage ]( { t: true }, '*' );
}
})(this,'message','postMessage');
// Usage
setTimeout(function(){
alert([
'window.postMessage: ' + !!window.postMessage,
'window.postMessage.complex: ' + ( window.postMessage && window.postMessage.complex )
].join('\n'))
}, 100)
@paulirish
Copy link

why does this need to be async? remember why the setTimeout?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment