views:

172

answers:

3

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.

+2  A: 

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.

Chris Nielsen
+1 good work-around
Fabian Neumann
I tried using this script but for some reason, I get errors when using it in 3.5 and not 3.6.JSON.parse errors specifically.
gmiernicki
Can you give us the exact error message you are getting? Can you show us the exact string that you are passing into JSON.parse? This would help diagnose the problem.
Chris Nielsen
A: 

Since you are clearly looking for a FF-olny solution, have you tried yourObject.toSource()?

Rakesh Pai
Per your comment, I tried to use toSource and toString, but these did not seem to help. I pass a handcoded JSON object in the worker and its decoded in the main thread. However, toSource when used an object has it coming out as undefined in the main thread.
gmiernicki
A: 

I found the solution to my own problem!

It seems that if the thread variable, even if declared globally, loses its .onmessage property if that said property was declared inside another function. If the property is instantiated on the global scope, then JSON messages are parsed correctly.

I'm still not sure I understand what's going on here, but at least I've figured out a way to pass objects around without having to rely on any additional stingify/json libraries.

If anyone could explain this to me so I have a better understanding, it would be appreciated :)

I setup a test case here: http://x.miernicki.com/ which logs the inter-thread messages to the firebug console if anyone cares. This helped me to get objects passed around in Fox3.5 and ultimately allowed me to see what the problem was.

gmiernicki