javascriptweb-workershared-worker

How to call shared worker from the web worker?


Is it possible to call a Shared Worker from the Web Worker?

Could you please give me an example.

In my case I have a few web workers and I need to share a singleton service between them.


Solution

  • The SharedWorker constructor is not currently available within the WorkerGlobalScope, so you will not be able to construct an instance like you would in an iframe or window.

    What you can do is, create a MessageChannel for each of your workers, and use it to communicate between the worker and sharedWorker. Though doing this would negate the need for an actual SharedWorker, since you could just as well use a single Worker instead.

    Example:

    var numWorkers = 4;
    var sharedWorker = new Worker("worker-shared.js");
    
    for(var i = 0; i < numWorkers; i++) {
      var dedicatedWorker = new Worker("worker-dedicated.js");
      var channel = new MessageChannel();
      dedicatedWorker.postMessage({sharedWorkerPort: channel.port1}, [channel.port1]);
      sharedWorker.postMessage({workerPort: channel.port2}, [channel.port2]);
    }
    

    Demo