从 SharedWorker 向 SharedWorker 发送消息 [英] Sending messages from SharedWorker to SharedWorker

查看:55
本文介绍了从 SharedWorker 向 SharedWorker 发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 SharedWorkers 的 MDN 文档 指出:

SharedWorker 接口代表一种特定类型的工作器,可以从多个浏览上下文访问,例如多个窗口、iframe甚至工作器.

The SharedWorker interface represents a specific kind of worker that can be accessed from several browsing contexts, such as several windows, iframes or even workers.

对我来说,这听起来好像 SharedWorkers 应该能够直接交换消息.但是,如果我尝试从另一个 SharedWorker 中访问 SharedWorker,即使用

To me this sounds as if SharedWorkers should be able to directly exchange messages. However, if I try to access a SharedWorker from within another SharedWorker, namely with

var worker = new SharedWorker("path/to/file.js");

我明白

ReferenceError: SharedWorker 未定义

ReferenceError: SharedWorker is not defined

是我误读了文档,还是有其他方法可以做到这一点?

Did I just misread the documentation, or is there another way to do this?

推荐答案

虽然你似乎无法从共享 worker 中创建共享 worker,但是你可以通过在主线程中创建它们来实现它们之间的通信,并且将一个的 MessagePort 对象传递给另一个.请注意,您必须在 postMessage 的传输列表参数中包含端口:它不能被复制.

Although you don't seem to be able to create a shared worker from a shared worker, you can communicate between them by creating them in the main thread, and passing the MessagePort object of one to the other. Note you have to include the port in the transfer list argument to postMessage: it can't be copied.

例如,在主线程中创建worker,并将其中一个的端口发送给另一个:

For example, in the main thread create the workers, and send the port of one to the other:

var myWorker1 = new SharedWorker("worker1.js");
myWorker1.port.start();

var myWorker2 = new SharedWorker("worker2.js");
myWorker2.port.start();

myWorker2.port.postMessage({worker1Port: myWorker1.port}, [myWorker1.port]);

在第一个 worker 中,您可以在端口上发送消息:

In the first worker you can send messages on a port:

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

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

然后在第二个工作程序中,您可以保存传入端口对象,并响应在其上收到的消息.

and then in the second worker you can save the incoming port object, and respond to messages received on it.

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

  port.onmessage = function(e) {
    var worker1Port = e.data.worker1Port;
    worker1Port.onmessage = function(e) {
      console.log('received in worker 2', e.data);
    };
  };
};

您可以在 http://plnkr.co/edit/XTOej1b1PHfWuC9LHeZc?p=预览

这篇关于从 SharedWorker 向 SharedWorker 发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆