Search code examples
javascriptjsonmultithreadingpostmessageweb-worker

How do you encode an Object in a Web Worker for it to be passed via postMessage?


Internally, Firefox will JSON encode an object passed via postMessage to and from the Web Worker. However, this only works in Trunk builds of Firefox (3.6+) and not in Firefox 3.5, so the question is really how to add backwards support of this operation to the current platform. The window.atob() and window.btoa() methods had been suggested before, but alas these are not available internally to the threads because they don't have access to the DOM.

Mozilla publicly states this on their developer wiki, but it has been noticed by many in the community that this happens. Check ejohn's blog test: http://ejohn.org/files/bugs/postMessage/

I've verified that this is the case as well, in 3.5, it passes only strings, and in 3.6 is will pass the object.


Solution

  • I haven't noticed the automatic JSON-encoding not working in Firefox 3.5, but I've mainly been working with Gears, which doesn't support it anyway.

    Try including a JSON utility in both the worker script and the parent script, then manually encode and decode it yourself. This works fairly well for me with Gears.

    This approach shouldn't break when Firefox begins automatically doing the JSON encoding for you, since the encoded JSON string will remain a string.