SharedWorker
What is a SharedWorker?
Section titled “What is a SharedWorker?”A SharedWorker is a Web Worker that is shared across all browsing contexts (tabs, windows, iframes) of the same origin. Unlike a Dedicated Worker, which exists only for one page, a SharedWorker lives until all connected tabs close. Think of it as a lightweight in-browser “service” — it can hold shared state, deduplicate network requests, and synchronize data across tabs without a backend.
Key differences from a Dedicated Worker
Section titled “Key differences from a Dedicated Worker”| Dedicated Worker | SharedWorker | |
|---|---|---|
| Instance per tab? | Yes — one per page | No — one shared across all tabs |
| Constructor | new Worker(url) | new SharedWorker(url) |
| Communication | worker.postMessage direct | worker.port.postMessage via MessagePort |
| Worker receives connect? | No | Yes — onconnect event fires on each new tab |
| Lifetime | Tied to the owning page | Until all connected tabs close |
The API
Section titled “The API”There are four key steps to using a SharedWorker.
Step 1 — In the main thread:
const worker = new SharedWorker('shared-worker.js');worker.port.start(); // must call start() to activate the portworker.port.postMessage('hello');worker.port.onmessage = (e) => console.log(e.data);Step 2 — In the worker (shared-worker.js):
const ports = [];self.onconnect = (e) => { const port = e.ports[0]; ports.push(port); port.start(); port.onmessage = (ev) => { // echo to all connected tabs for (const p of ports) p.postMessage('echo: ' + ev.data); };};Why SharedWorker needs multiple tabs
Section titled “Why SharedWorker needs multiple tabs”The real power of SharedWorker is cross-tab shared state. Opening one tab barely demonstrates it — you need at least two. That is why the runnable below opens in StackBlitz, where you can open two browser panes pointing at the same URL.
Runnable: shared counter across tabs (StackBlitz)
Section titled “Runnable: shared counter across tabs (StackBlitz)”Needs multiple tabs / a SharedWorker context — open in StackBlitz to run.