Search code examples
javascriptweb-workerpubnub

Can a web worker or something similar handle window close events?


I'm working on a project that would have the user opening tabs that each connect to a PubNub channel and listens for events. These open tabs are then represented in a management tab so the user can see all the tabs that are connected. Currently, we're using their presence to see who is connected which also fires messages showing join, leave, and timeout messages.

The issue comes down to if the user simply closes a tab, I can't fire an unsubscribe message to the channel and thus I have to wait for PubNub to call a timeout on that connection to remove it from the management tab. I've tweaked their heartbeat option to be a lot shorter but it would really be nice to have that be a lot more up to the second when those connections get closed.

My thought was maybe a Web Worker or something similar that can maybe be spawned to simple take care of sending an unsubscribe message but it seems that may not be possible as from what I understand the web worker becomes unusable if the parent page that spawned it gets closed?

Is there a way to do something like this or is my best bet to just let the timeout take effect and deal with the manager tab just waiting until the timeout gets called?


Solution

  • PubNub and Browser Window/Tab Close Events

    The WebWorker might be an option but it is highly browser dependent. And if you are not worried about browser dependencies then you can just rely on the browser's support for sendBeacon or onbeforeunload event to do the unsubscribe.

    But you can also enable TCP_FIN on your Presence add-on for your PubNub keys which will send a leave event when the tab is unloaded. Careful though as this could have page unload performance issues if you are subscribed to a lot of channels because it is a blocking call.