demo · v148
Cross-Tab Counter
This page connects to a SharedWorker. Open the same URL in another tab and the worker links the two — clicking +1 in one tab updates the count in the other. On Chrome 148+ it also works on Android.
—
Heads up:
SharedWorker isn't available in this browser. Try Chrome 148+, Firefox, or Safari to see the demo work.
the code
// In every tab:
const worker = new SharedWorker("./worker.js");
worker.port.addEventListener("message", (e) => {
// Same payload arrives in every tab that's connected.
});
worker.port.start();
worker.port.postMessage("increment");
// In worker.js:
const ports = new Set();
let count = 0;
self.addEventListener("connect", (event) => {
const port = event.ports[0];
ports.add(port);
port.addEventListener("message", (e) => {
if (e.data === "increment") count++;
for (const p of ports) p.postMessage({ count, tabs: ports.size });
});
port.start();
});
see also
- SharedWorker on Android — feature index
- ChromeStatus entry
- HTML spec: SharedWorker
implementation reference
Need the exact API surface, compatibility boundaries, errors, lifecycle, and source links? Read the matching gendn reference ↗