嵌套共享工作者
是否可以(即使不明智)在另一个 SharedWorker 的处理程序中实例化一个 SharedWorker ?
// Code in sharedworker.js
onconnect = function(e) {
var port = e.ports[0];
port.onmessage = function(e) {
port.postMessage("Hello"); // This is sent.
var worker = new SharedWorker("worker.js");
post.postMessage("Goodbye"); // In my tests, this is not sent.
}
}
// Code in main.js
var worker = new SharedWorker('sharedworker.js');
worker.port.onmessage = function(e) {
window.console.log(e.data);
}
worker.port.postMessage("Start");
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,
SharedWorker< /code> 接口
仅在
Window
上下文中公开。您无法直接从另一个SharedWorker
内部或从专用Worker
内部创建SharedWorker
。但是,您可以做的是从同一
Window
上下文启动两个SharedWorker
实例,并从 MessagePort ="https://developer.mozilla.org/en-US/docs/Web/API/MessageChannel" rel="nofollow noreferrer">MessageChannel
对象。这样,您的两个 SharedWorker 实例将能够直接相互通信,就像一个实例化了另一个实例一样:在您的窗口脚本中,您将看到类似以下内容
:脚本:
不幸的是,StackSnippets iframe 不允许创建
SharedWorker
,所以我必须外包 Glitch 项目中的“nofollow noreferrer">现场演示 。No, the
SharedWorker
interface is only exposed inWindow
contexts. You can't create aSharedWorker
directly from inside anotherSharedWorker
nor from inside a dedicatedWorker
.What you can do however is to start both
SharedWorker
instances from the sameWindow
context and pass to both of them aMessagePort
from aMessageChannel
object. This way, both yourSharedWorker
instances will be able to communicate one with each other directly, just like if one did instantiate the other:In your window's script you'd then have something like:
And in you worker scripts:
Unfortunately, StackSnippets iframes don't allow to create a
SharedWorker
, so I have to outsource the live demo into a Glitch project.应该是
port.postMessage("Goodbye");
而不是post.postMessage("Goodbye");
吗?Should that be
port.postMessage("Goodbye");
instead ofpost.postMessage("Goodbye");
?