共享工作者在重新加载页面上终止 [英] Shared worker is teminated on reloading page

查看:42
本文介绍了共享工作者在重新加载页面上终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么共享工作者在重新加载页面时死了?应该是复活了我该如何解决这个问题?

Why is Shared Worker dead on reloading page? It must've revived. How can I fix this issue?

var port = new SharedWorker('/app/worker-5n1261e73b.js').port;
port.onmessage = function(e){
    console.log(e.data);
};
port.start();

worker-5n1261e73b.js

onconnect = function(e){
    var port = e.ports[0];
    port.onmessage = function(e){
         console.log(e.data);
    };
    port.start();
    port.postMessage('Connected');
};

推荐答案

当页面重新加载时,javascript 将再次执行,创建与 SharedWorker 的连接的代码也是如此.

When a page is reloaded the javascript is executed again and so is the code that creates the connection to your SharedWorker.

onconnect() 事件处理程序,在您的 Sharedworker 中,不知道该选项卡是重新加载还是一个全新的选项卡,因此它只是将该选项卡注册为新的连接端口,停止与前一个选项卡端口的通信(如果页面已重新加载).换句话说,重新加载的页面为 Sharedworker 获得了一个新的端口号.

The onconnect() event handler, in your Sharedworker, does not know whether the tab was reloaded or whether it is an entirely new tab, so it just registers the tab as a new connected port, stopping the communication with the previous tab port (if the page was reloaded). In other words, the reloaded page got a new port number for the Sharedworker.

如果您当时只打开了一个选项卡,请确保在重新加载页面时已停止并重新创建 Sharedworker,但如果您当时打开了多个页面,则 Sharedworker 不会因为其他原因而停止工作实时连接.

If you only had one tab open at that time, for sure the Sharedworker is stopped and recreated when reloading the page, but if you had more than one page opened by that time, the Sharedworker does not stop working because of the other live connections.

这篇关于共享工作者在重新加载页面上终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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