demo · v140

Connection Counter

The gauge shows how many same-origin tabs are connected to this SharedWorker right now. Open another tab on this page; the counter goes up. Close it; the counter goes down. The cheapest way to discover "how many tabs of my app are open" without polling.

connected tabs

// SharedWorker keeps a Set of connected ports.
let ports = new Set();
onconnect = (e) => {
  const p = e.ports[0];
  ports.add(p);
  broadcast();
  p.onmessage = (m) => { if (m.data === "bye") { ports.delete(p); broadcast(); } };
  p.start();
};
function broadcast() {
  for (const p of ports) p.postMessage({ count: ports.size });
}

// Page side:
window.addEventListener("beforeunload", () => w.port.postMessage("bye"));

see also