Shared Workers for Cross-Tab Communication
You'll learn: How to use SharedWorker to create a single worker instance that multiple browser tabs and windows can connect to and share.
What Makes Shared Workers Different
In previous lessons, you created dedicated Web Workers that belonged to a single page. A SharedWorker is different—it's a worker that can be accessed by multiple browsing contexts (tabs, windows, iframes) from the same origin. Think of it like a shared office space: instead of each employee having their own room (dedicated worker), multiple employees can connect to and use the same conference room (shared worker).
Creating a Shared Worker
You create a SharedWorker similarly to a regular worker, but the connection model is different:
// In any tab/window
const sharedWorker = new SharedWorker('shared-worker.js');
Communication Through Ports
Unlike dedicated workers, SharedWorkers use message ports for communication. Each connecting page gets its own port:
// In your page
sharedWorker.port.start(); // Activate the port
sharedWorker.port.postMessage('Hello from Tab 1');
sharedWorker.port.onmessage = (event) => {
console.log('Reply:', event.data);
};
Inside the worker, you handle connections through the onconnect event:
// shared-worker.js
onconnect = (event) => {
const port = event.ports[0];
port.onmessage = (e) => {
// Receive message from a connected tab
port.postMessage(`Received: ${e.data}`);
};
};
Real-World Use Cases
Shared workers excel at maintaining shared state across tabs—like synchronized notifications, shared WebSocket connections, or centralized cache management that all tabs can access.
Key Takeaway: SharedWorker creates a single worker instance shared across multiple tabs from the same origin, using message ports for communication with each connected context—perfect for cross-tab coordination and shared resources.