v160 · dom · workers · practical use
Connection hub
The classic reason to use a SharedWorker: one hub that every tab of your app connects to — for presence, a shared socket, or a single cache. The hub learns about each client from a connect event. HTML fires that event from two different algorithms: run a worker for the very first client, and the SharedWorker constructor for every client after that. Both say data is "". This hub records the real data of each client’s own connect event.
Checking for SharedWorker…
The hub’s roster
This page joins the hub connection-hub automatically. Add more connections from this page, or open the page in more tabs — every tab sees the same roster, because they all talk to one worker.
| # | Client | connect fired by | e.data | typeof | State |
|---|---|---|---|---|---|
| — | — | — | — | — | — |
the hub, verbatim
// hub worker
const clients = [];
onconnect = (e) => {
const port = e.ports[0]; // the handshake — unchanged in 160
clients.push({ port, data: e.data });
// e.data: "" in Chrome 160+ / Firefox / Safari, null in Chrome ≤159 —
// for the FIRST client (run a worker) and for every LATER client
// (SharedWorker constructor, existing worker) alike.
for (const c of clients) c.port.postMessage({ online: clients.length });
};
Nothing about the hub’s behaviour should depend on e.data — the connect event carries no payload. Send a hello message over the port instead (as this page does with its tab label) and treat connect purely as “a port arrived”. To reproduce the legacy null on Chrome 160+, launch with --disable-blink-features=SharedWorkerConnectEventEmptyStringData.