Skip to main content

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

FeatureWorker (Dedicated)SharedWorker
Used byOne pageSeveral tabs/windows
Created withnew Worker('worker.js')new SharedWorker('worker.js')
Communication channelpostMessage directlyVia a port object
LifetimeWhile the tab is openWhile at least one context is connected
Accessible from other tabsNoYes (if the same origin)

Example of SharedWorker in action

1. Code in shared-worker.js

javascript
// 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)

javascript
// 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

javascript
// 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

ScenarioWhy SharedWorker helps
Shared chat between tabsmessages can be synchronized
Background data processingone tab computes, everyone gets the result
Shared WebSocket subscriptionone connection for all tabs (saves resources)
Shared cache/IndexedDB logicone background for everyone
State synchronizationfor example, a shared auth token between tabs

How SharedWorker interacts

javascript
[ Tab 1 ] [ Tab 2 ] [ Iframe ] │ │ │ └─────▶ [ SharedWorker Thread ] ◀─────┘ ▲ │ │ (ports[]) ▼ logic processing

All 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() and port.onmessage.

Security

  • Workers are isolated, they have no access to the DOM, window, or document.
  • 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

FeatureDescription
What it doesLets several pages (tabs) of one site share a single JS thread
Main benefitSharing logic and data between tabs
CommunicationVia MessagePort (port.postMessage / port.onmessage)
LifecycleWhile at least one client is open
No DOM accessOnly message exchange
Typical scenariosShared WebSocket, cache, state synchronization, cross-tab chat

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.