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.
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.
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.
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