Search code examples
javascriptweb-workershared-worker

Can SharedWorkers use global variables from other shared workers?


I need to do some heavy lifting and find it a bit tedious to have to reformat my entire code and was wondering "Can SharedWorkers use global variables from other shared workers?".

If so can someone give a simple demonstration I am fairly new to SharedWorkers. I saw a thread that was very close to answering my question but did not provide a example see: the second answer with @Raynos

What's the difference between Shared Worker and Worker in HTML5?

I also looked at the main documentation and it is a bit lack luster with answering this. It just goes on about using a single shared worker to talk to to other pages . Anyhow , a example of this in action would be freaking amazing , I've been searching for a long time and come up with nothing thus far .


Solution

  • SharedWorkers have limited support - just Firefox and Chrome. They're probably best avoided unless you have a known audience.

    To answer the question: a SharedWorker can not directly access variables from another SharedWorker.

    The only way to communicate with workers is to post and receive messages. A SharedWorker could initiate another SharedWorker but it would still need to pass the values it wanted to share.

    In general, SharedWorkers could be useful where:

    1. your application opens multiple windows or frames
    2. any instance can set values and initiate processing, and
    3. the result would be posted back to some or all instances.

    That's a fairly unusual use-case.