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