JavaScript: How to know if a connection with a shared worker is still alive?

html, javascript, web-applications, web-worker, webkit

Solution

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'} );
});

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;
    }
}

Problem

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]); }; ``` 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. 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. 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. EDIT: 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.

Original source