Suggest an editImprove this articleRefine the answer for “What does SharedWorker do?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)**`SharedWorker`** is a JavaScript thread that several tabs, iframes, or windows of the same `origin` can use at once, exchanging messages through a `port` object. **Key point:** unlike a regular `Worker`, a SharedWorker stays alive as long as at least one context is connected, rather than dying with the closing of a single tab.Shown above the full answer for quick recall.Answer (EN)Image## 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 ```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 | 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 ```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 | 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 |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.