[removed] How to know if a connection with a shared worker is still alive?

后端 未结 4 614
盖世英雄少女心
盖世英雄少女心 2021-02-01 16:47

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         


        
4条回答
  •  遇见更好的自我
    2021-02-01 17:19

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

提交回复
热议问题