Spawning a Shared Worker in a Dedicated Worker

孤者浪人 提交于 2019-12-31 03:21:07

问题


I'm playing around with WebWorkers. Somehow I had the idea to let the different instances of a page know when another one is closed. Therefore I wrote a Shared Worker and it works fine.

But now I want a Dedicated Worker to act as an interface to the Shared Worker. So that expensive actions in the UI won't affect the continous communication with the Shared Worker. But I get the error, SharedWorker was not defined. An idea would be to use MessageChannel, but I want it to run at least in Firefox and Chrome and as far I know, Firefox still doesn't have a working implementation of MessageChannel.

So - are there any workarounds for this problem?


回答1:


You can't create a shared worker object in the dedicated worker. However, you can create a shared worker in the main UI thread and pass its port to the dedicated worker, so they can communicate directly.

As an example, in main thread create both workers, and transfer the port object of the shared to the dedicated:

var sharedWorker = new SharedWorker("worker-shared.js");
sharedWorker.port.start();

var dedicatedWorker = new Worker("worker-dedicated.js");
dedicatedWorker.postMessage({sharedWorkerPort: sharedWorker.port}, [sharedWorker.port]);

In the shared worker you can post messages on this port:

self.onconnect = function(e) {
  var port = e.ports[0];

  self.setInterval(function() {
    port.postMessage('sent from shared worker');
  }, 1000);
};

And in the dedicated you can react to them

self.onmessage = function(e) {
  var sharedWorkerPort = e.data.sharedWorkerPort;
  sharedWorkerPort.onmessage = function(e) {
    console.log('received in dedicated worker', e.data);
  };
};

You can see this working at http://plnkr.co/edit/ljWnL7iMiCMtL92lPIAm?p=preview



来源:https://stackoverflow.com/questions/30741686/spawning-a-shared-worker-in-a-dedicated-worker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!