JavaScript:如何知道与共享工作者的连接是否仍然存在? [英] JavaScript: How to know if a connection with a shared worker is still alive?
问题描述
我正在尝试使用共享工作者来维护Web应用程序的所有窗口/选项卡的列表。因此,使用以下代码:
I'm trying to use a shared worker to maintain a list of all the windows/tabs of a web application. Therefore following code is used:
//lives in shared-worker.js
var connections=[];//this represents the list of all windows/tabs
onconnect=function(e){
connections.push(e.ports[0]);
};
每次创建窗口时,都会与共享工作者建立连接。 js
worker和worker将窗口的连接添加到 connections
列表。
Everytime a window is created a connection is established with the shared-worker.js
worker and the worker adds the connection with the window to the connections
list.
当用户关闭窗口时,它与共享工作程序的连接将过期,应从 connections
变量中删除。但是我找不到任何可靠的方法。
When a user closes a window its connection with the shared worker expires and should be removed from the connections
variable. But I don't find any reliable way to do that.
查看规范 connections
变量的对象似乎没有包含属性/函数来检查是否连接仍然存在。
Looking at the specification the objects of the connections
variable doesn't seem to hold a property/function to check if the connection is still alive.
是否可能?
同样,总体目标是拥有所有窗口/标签的列表。
Is it possible?
Again, the overall goal is to have the list of all windows/tabs.
编辑:一种方法是将共享工作人员的消息发送到Windows并期待回复。如果共享工作者没有收到回复,那么它将认为该窗口已关闭。在我的实验中,这种方法并不可靠;问题是没有办法判断一个窗口是关闭还是只是花了很长时间才能回复。
An approach would be to make the shared worker message the windows and expect a reply. If the shared worker doesn't receive a reply then it would assume that the window is closed. In my experiments this approach has not shown to be reliable; the problem being that there is no way to tell if a window is closed or is just taking a long time to reply.
推荐答案
这与beforeunload一样可靠,但似乎有效(在Firefox和Chrome中测试过)。我绝对赞成使用轮询解决方案。
This is only as reliable as beforeunload, but seems to work (tested in Firefox and Chrome). I definitely favour it over a polling solution.
// Tell the SharedWorker we're closing
addEventListener( 'beforeunload', function()
{
port.postMessage( {command:'closing'} );
});
然后处理SharedWorker中端口对象的清理。
Then handle the cleanup of the port object in the SharedWorker.
e.ports[0].onmessage = function( e )
{
const port = this,
data = e.data;
switch( data.command )
{
// Tab closed, remove port
case 'closing': myConnections.splice( myConnections.indexOf( port ), 1 );
break;
}
}
这篇关于JavaScript:如何知道与共享工作者的连接是否仍然存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!