Using web workers

Code in Examples section broken?

Unless I don't understand what it's supposed to do, the code in the Examples section seems to be broken.  In my browser (FF 12.0), it just prints 5.  Someone who knows this stuff better than me should fix it!  :)

Complete for general stuff and Chrome

On 06.24.2011 Ebidel worked on the page. The compat table is complete, and he reviewed and edited the docs. Don't know much about FF extensions, so that part was untouched.


Workers in extensions - Threadsafety

Workers in extensions don't have access to the the Components object from their thread making it nearly impossible to create XPCOM objects in a worker. Objects passed to workers will always be sent as JSON making it impossible to inject one into the worker thread. As such I can't think of any special reason you'd have to worry about threadsafety in extensions differently than normal web pages. If someone does need to use XPCOM objects in threaded code they can use the Thread Manager instead, and will need to look into thread-safety for the created objects.

I'm certainly not an expert on workers, threads or on Mozilla's use of them though, so I'm refraining from changing this article. Maybe there is some extra worry about threads in extensions, or some way to create Components/Services that I'm not aware of.

Posting messages both ways

I know that I can postMessage from a worker to its 'parent' by calling postMessage(). Can I post from the parent back to the worker by worker.postMessage() ?

Similarly, I can set worker.onmessage = function(){ ... } to handle messages from the worker. Am I right in thinking that you can (inside the worker) set onmessage = function(){ ... } to handle messages sent TO the worker as above?

I couldn't find any (explicit) info on this on MDC, so maybe this is worth adding.