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
...How about using the approach you suggest in the edit, i.e. use a keep-alive ping, BUT:
Just before closing any unresponsive connection, send a "please reconnect" message through it, so that if a window isn't really closed, just busy, it'll know it has to re-connect?
This technique should probably be combined with sending explicit "I'm closing now" messages from window onunload events, as per @Adria 's solution, so that normal window termination is handled efficiently and without any delay.
This is still somewhat unreliable, in that very busy windows might drop off the SharedWorker's list temporarily, before later re-connecting... but actually I don't see how you could do much better: Consider that if a window hangs, practically speaking that's not going to be differentiable from a it being "busy" for some indefinitely long time, so you can't really catch one without catching the other (in any finite time, anyway).
Depending on your application, having very busy windows temporarily getting de-listed may or may not be a big problem.
Note that the keep-alive pings should be sent from the SharedWorker to windows, which should then respond: If you try simply using setTimout() in the windows, you run into the problem that setTimeout() on background windows can be long delayed (up to 1 second on current browsers I believe), while the SharedWorker's setTimeout()s should run on schedule (give or take a few ms), and idling background windows will wake up and respond immediately to posted SharedWorker messages.
Here's a neat little demo of this technique, that:
sharedworker.html
Shared Worker Test
This Window's ID: ???
Active Window ID: ???
Window Count: ???
Other Window IDs: ???