Serialization of HTML5 web worker postMessage parameters in webkit
I played around with html5 web workers today. I quickly ran into an issue with chrome. Chrome (and probably also Safari) limit the messages that can be passed around to strings. The spec seems to allow arbitrary objects though, which works in firefox. Luckily Chrome supports native json, so here is a quick workaround.
// in the worker if(navigator.userAgent.indexOf('WebKit')) { var _postMessage = postMessage; postMessage = function(data) { _postMessage(JSON.stringify(data)); } } // in the page worker.onmessage = function(e) { // assign it to a variable, e.data seems to be read-only var data = e.data; if(navigator.userAgent.indexOf('WebKit') != -1) { data = JSON.parse(data); } // ..
In the worker monkey patching is easily possible. But I'm not aware of a nice way to intercept events so, I just put the decoding in the event handler. If I would need this in a lot of places I would probably write a higher order function the decode the argument.