Is there a way for SharedWorker to tell if it is about to get closed?

1.4k Views Asked by At

Is there a way to tell that the SharedWorker is about to get closed, something like the beforeunload event that window has?

I need this information inside of the worker to signal server of closing of web socket etc.

2

There are 2 best solutions below

7
Xinchao On

No.

But SharedWorker will be alive as long as there is any live page holding a reference to it (through new SharedWorker()). So what you can do is to post a message to your SharedWorker when your page is about to go away (pagehide event), and your SharedWorker can keep track of how many pages are alive and close the WebSocket when the live count drops to zero.

However, do watch out for the definition of "live page". Chrome (and other browsers as well) tries very hard to optimize the browser performance and energy impact. Chrome has this Tab Discarding feature where it will discard background pages when there is pressure on the memory. Discarding a page will throw away the page data without closing the window, so that when user clicks the windows again Chrome can reload the page. This usually isn't an issue for simple website, but given that you are running websocket inside SharedWorker this could have some implications on your overall protocol design. In particular, if all of your pages are discarded, your SharedWorker dies as well. And discarding a page has absolutely zero notification.

1
Ambuj sahu On

you can read about it in 10.2.3 The worker's lifetime! section. Here it is mentioned that a shared worker is permissible as long as

  • the user agent has a navigable whose active document is not completely loaded. So once the active document is loaded completely it no longer alive.
  • Other condition is that its owner set has been empty for more than a short implementation-defined timeout value