What does SharedWorker do?
What SharedWorker is
SharedWorker is a JavaScript thread that can be used by several contexts (tabs, iframes, windows) at the same time, as long as they are loaded from the same
origin(protocol + host + port).
Unlike a regular Worker, which "dies" when its tab closes, a SharedWorker stays alive as long as at least one window remains connected.
Difference from a regular Web Worker
| Feature | Worker (Dedicated) | SharedWorker |
|---|---|---|
| Used by | One page | Several tabs/windows |
| Created with | new Worker('worker.js') | new SharedWorker('worker.js') |
| Communication channel | postMessage directly | Via a port object |
| Lifetime | While the tab is open | While at least one context is connected |
| Accessible from other tabs | No | Yes (if the same origin) |
Example of SharedWorker in action
1. Code in shared-worker.js
// shared-worker.js
onconnect = (event) => {
const port = event.ports[0];
console.log('New connection');
port.postMessage('Hi, tab!');
port.onmessage = (e) => {
console.log('Message from the tab:', e.data);
// Send a reply back
port.postMessage(`Received: ${e.data}`);
};
};2. Code on each tab (main.js)
// main.js
const shared = new SharedWorker('shared-worker.js');
const port = shared.port;
// Activate the channel
port.start();
// Listen for replies from the worker
port.onmessage = (e) => {
console.log('Reply from SharedWorker:', e.data);
};
// Send a message to the worker
port.postMessage('Hi from the tab!');What happens:
- All tabs connect to the same worker;
- All of them receive messages through their own
port; - The worker can coordinate them (for example, broadcasting shared data to everyone).
How onconnect works
When a new tab creates new SharedWorker(), the browser does not create a new thread if the worker already exists.
It simply fires the onconnect event, passing it a MessagePort object that represents the communication channel.
This way, one SharedWorker can manage dozens of ports (tabs).
Example of broadcasting to all tabs
// shared-worker.js
const ports = [];
onconnect = (e) => {
const port = e.ports[0];
ports.push(port);
port.start();
port.onmessage = (event) => {
// Broadcast the message to all connected tabs
for (const p of ports) {
p.postMessage(`From tab: ${event.data}`);
}
};
};Now, if you open two tabs:
- tab 1 sends
port.postMessage("Hi"), - both tabs receive
"From tab: Hi".
That is already a real chat between tabs!
General use cases
| Scenario | Why SharedWorker helps |
|---|---|
| Shared chat between tabs | messages can be synchronized |
| Background data processing | one tab computes, everyone gets the result |
| Shared WebSocket subscription | one connection for all tabs (saves resources) |
| Shared cache/IndexedDB logic | one background for everyone |
| State synchronization | for example, a shared auth token between tabs |
How SharedWorker interacts
[ Tab 1 ] [ Tab 2 ] [ Iframe ]
│ │ │
└─────▶ [ SharedWorker Thread ] ◀─────┘
▲ │
│ (ports[])
▼
logic processingAll tabs connect to one worker thread. The worker exchanges messages with each tab through its port.
What is important to remember
- SharedWorker works only within a single origin (
https://example.com!=http://example.com). - Not supported inside Service Workers (those are a different type of worker).
- Does not work in some older browsers or in Safari on iOS.
- Communication happens via
port.postMessage()andport.onmessage.
Security
- Workers are isolated, they have no access to the DOM,
window, ordocument. - Data is passed by copy (structured clone).
- You can use Transferable objects (
ArrayBuffer) for fast exchange.
A simple analogy
Imagine SharedWorker as an office server in a company.
Each employee (tab) can connect to the server. The server stores shared data and broadcasts updates to everyone. As long as at least one employee is working, the server stays alive.
When everyone closes their tabs, the server shuts down automatically.
Summary
| Feature | Description |
|---|---|
| What it does | Lets several pages (tabs) of one site share a single JS thread |
| Main benefit | Sharing logic and data between tabs |
| Communication | Via MessagePort (port.postMessage / port.onmessage) |
| Lifecycle | While at least one client is open |
| No DOM access | Only message exchange |
| Typical scenarios | Shared WebSocket, cache, state synchronization, cross-tab chat |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.