Web Workers and Messaging: Threads, postMessage, Transferables and BroadcastChannel
Run JavaScript off the main thread: creating classic and module workers, the worker global scope, the execution model, errors, MessageChannel, structured clone vs transfer, a promise-based RPC wrapper, SharedArrayBuffer and Atomics, cross-window postMessage and BroadcastChannel.
kvi5hnuCode Sprout team member9 min readOn this page
A page's JavaScript normally runs on one thread, the main thread, which also handles user input, layout and painting. A function that computes for 300 ms freezes the page for 300 ms: clicks go unanswered, animations stutter and typing lags. Web Workers let you run code on separate threads. Workers can't touch the DOM and share no variables with the page; they communicate only by passing messages. This design avoids the shared-memory bugs of classic multithreading (race conditions and deadlocks) by default.
Creating a worker
A worker runs a separate script file:
// main.js (in the page)
const worker = new Worker(new URL("./stats-worker.js", import.meta.url), { type: "module", name: "stats" });
worker.postMessage({ numbers: [3, 1, 4, 1, 5, 9, 2, 6] }); // send work
worker.addEventListener("message", (event) => { // receive results
console.log("mean:", event.data.mean);
});
worker.addEventListener("error", (event) => {
console.error(`worker failed: ${event.message}`);
});
// stats-worker.js (runs in its own thread)
self.addEventListener("message", (event) => {
const { numbers } = event.data;
const mean = numbers.reduce((a, b) => a + b, 0) / numbers.length;
self.postMessage({ mean });
});
- The script URL must be same-origin with the page. A relative string is resolved against the page's URL;
new URL(..., import.meta.url)resolves it against the current module instead, which bundlers also recognize. { type: "module" }makes the worker an ES module that can useimport, supported in all major browsers since 2023. A classic worker (the default) loads extra code withimportScripts("a.js", "b.js"), which downloads and runs the files synchronously, something that's acceptable on a worker thread.worker.terminate()stops a worker immediately from outside; inside,self.close()stops it.
Inside a worker
A worker's global object is a WorkerGlobalScope, available as self (or globalThis). It has all of core JavaScript, plus many web APIs: fetch, setTimeout and setInterval, IndexedDB, WebSocket, crypto, console, TextEncoder, OffscreenCanvas, and even Worker to start sub-workers. It also has a read-only location and a navigator.
It doesn't have window, document or any DOM, or localStorage. All rendering must happen on the main thread, so a worker sends back data, and the page updates the DOM.
The execution model
A worker runs its script from top to bottom, then enters its own event loop, handling messages, timers and fetches, just like a page (article 94). While it has a message listener, it stays alive waiting for messages. Each worker is an independent thread with its own memory, so starting one costs a few megabytes and some milliseconds: create workers for substantial work and reuse them, rather than starting one per small task.
Errors
An uncaught exception inside a worker fires an error event on the worker's global scope, and then, unless a handler calls preventDefault(), on the Worker object in the page. The event provides message, filename and lineno. Unhandled rejections inside a worker fire unhandledrejection on self. If a message can't be deserialized, a messageerror event fires instead of message. A failing worker isn't restarted automatically.
How messages are copied: structured clone and transfer
postMessage copies its argument with the structured clone algorithm (article 116): plain objects, arrays, Dates, Maps, Sets, typed arrays, Blobs and errors can be sent; functions, DOM nodes and class prototypes can't. The receiver gets an independent copy, so there's no shared state to corrupt.
Copying a large ArrayBuffer (an image, audio, a big array of numbers) takes time and doubles memory use. Listing it in the transfer list, the second argument, moves it instead: the memory changes owner instantly, and the sender's buffer becomes detached, unusable with a byteLength of 0. MessagePorts, ImageBitmaps, OffscreenCanvases and streams can be transferred too.
![The main thread and a worker thread each have their own global scope; postMessage(data) delivers a structured-clone copy, while postMessage(buf, [buf]) transfers the ArrayBuffer, leaving the sender's buffer detached with byteLength 0](https://code-sprout-content.laxmi.solutions/asset/2026/11/js-worker-messaging-nkn3djfmzfwldzjk.png)
Worker threads aren't available in plain Node scripts in the same form, but the same messaging primitives are: MessageChannel creates a pair of connected ports, which behave exactly like the two ends of a worker connection:
async function main() {
// 1. A MessageChannel: two connected ports; what one posts, the other receives
const { port1, port2 } = new MessageChannel();
const received = new Promise((resolve) => {
port2.addEventListener("message", (event) => resolve(event.data), { once: true });
});
port2.start(); // needed with addEventListener (onmessage starts it)
const settings = { theme: "dark", since: new Date(0), tags: new Set(["a"]) };
port1.postMessage(settings);
settings.theme = "light"; // changing the original afterwards...
const copy = await received;
console.log(copy.theme, copy.since instanceof Date, copy.tags.has("a")); // ...doesn't affect the copy
// 2. Transferring an ArrayBuffer moves it instead of copying it
const buffer = new Float64Array(1_000_000).buffer; // 8 MB
const arrived = new Promise((resolve) => { port2.onmessage = (event) => resolve(event.data); });
port1.postMessage(buffer, [buffer]); // second argument: the transfer list
console.log("sender byteLength after transfer:", buffer.byteLength);
console.log("receiver byteLength:", (await arrived).byteLength);
// 3. structuredClone can transfer too
const bytes = new Uint8Array([1, 2, 3]);
const moved = structuredClone(bytes, { transfer: [bytes.buffer] });
console.log(bytes.length, moved);
port1.close();
port2.close();
}
main();
dark true true
sender byteLength after transfer: 0
receiver byteLength: 8000000
0 Uint8Array(3) [ 1, 2, 3 ]
Messages are delivered asynchronously, as tasks on the receiver's event loop, in the order they were sent. A port must be started to receive: assigning onmessage starts it automatically, while addEventListener("message", ...) requires calling port.start().
Ports and channels
Every worker comes with a hidden pair of ports, which is what worker.postMessage and self.postMessage use. With new MessageChannel(), you can create extra channels and transfer a port to a worker (or an iframe), for example to connect two workers directly so their messages don't pass through the main thread:
const { port1, port2 } = new MessageChannel();
parserWorker.postMessage({ type: "connect" }, [port1]);
rendererWorker.postMessage({ type: "connect" }, [port2]);
// the two workers now talk over their ports; event.ports[0] receives the port on arrival
A promise-based worker API
Raw messages are awkward when you have several kinds of requests in flight at once: which reply belongs to which request? The usual solution tags each request with an ID and keeps a map of pending promises (using Promise.withResolvers, article 95). The example runs both sides over a MessageChannel; in a browser, one side is the Worker and the other is the worker's self:
// The "worker side": answers { id, method, args } messages on a port
function serve(port, methods) {
port.onmessage = async ({ data: { id, method, args } }) => {
try {
port.postMessage({ id, result: await methods[method](...args) });
} catch (err) {
port.postMessage({ id, error: err.message });
}
};
}
// The "page side": turns each request into a promise, matched to its reply by id
function connect(port) {
let nextId = 0;
const pending = new Map();
port.onmessage = ({ data: { id, result, error } }) => {
const { resolve, reject } = pending.get(id);
pending.delete(id);
if (error === undefined) resolve(result);
else reject(new Error(error));
};
return (method, ...args) => {
const { promise, resolve, reject } = Promise.withResolvers();
const id = nextId++;
pending.set(id, { resolve, reject });
port.postMessage({ id, method, args });
return promise;
};
}
async function main() {
const { port1, port2 } = new MessageChannel(); // in a browser: a Worker and its global scope
serve(port2, {
sum: (...numbers) => numbers.reduce((a, b) => a + b, 0),
slowSquare: (n) => new Promise((resolve) => setTimeout(() => resolve(n * n), 20)),
fail: () => { throw new Error("not allowed"); },
});
const call = connect(port1);
console.log(await Promise.all([call("slowSquare", 12), call("sum", 1, 2, 3)]));
try {
await call("fail");
} catch (err) {
console.log("rejected:", err.message);
}
port1.close();
}
main();
[ 144, 6 ]
rejected: not allowed
The replies to slowSquare and sum come back in a different order from the requests, but each promise gets its own result. Errors cross as messages and become rejections on the calling side. Libraries such as Comlink generalize this pattern by using proxies (article 105) so that a worker's functions can be called almost as if they were local.
Shared memory: SharedArrayBuffer and Atomics
For special cases such as audio processing, physics engines or code compiled to WebAssembly, copying is too slow and threads need to share memory. A SharedArrayBuffer posted to a worker isn't copied or transferred: both threads see the same bytes. Concurrent access then needs Atomics operations (Atomics.add, Atomics.compareExchange, Atomics.wait and Atomics.notify) to avoid race conditions.
Because shared memory enables precise timers that could be used for Spectre-style attacks, browsers enable SharedArrayBuffer only on cross-origin isolated pages, served with the headers Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp. self.crossOriginIsolated tells you whether that's the case.
Messaging between windows: postMessage
The same postMessage mechanism works between windows: a page and an <iframe>, a pop-up, or the page that opened it. This is the standard, safe way for code from different origins to communicate, for example an embedded payment form telling the host page the payment succeeded:
// in the parent page: send to the iframe, but only if it's still showing the expected origin
frame.contentWindow.postMessage({ type: "theme", value: "dark" }, "https://pay.example");
// in the iframe (or any window): ALWAYS check who sent the message
window.addEventListener("message", (event) => {
if (event.origin !== "https://shop.example") return; // ignore everyone else
if (event.data?.type === "theme") applyTheme(event.data.value);
event.source.postMessage({ type: "ack" }, event.origin); // reply to the sender
});
The second argument, the target origin, prevents the message from being delivered if the window has navigated to another site. Never use "*" for anything sensitive. On the receiving side, any site can send you messages, so checking event.origin is essential, and the data should be validated like any other untrusted input.
BroadcastChannel: talking to every tab
BroadcastChannel sends a message to every other context of the same origin that has opened a channel with the same name: tabs, iframes and workers. It's ideal for keeping tabs in sync (cart contents, logout, theme changes) without going through storage events:
async function main() {
// Every BroadcastChannel with the same name receives messages posted by the others
const sender = new BroadcastChannel("cart");
const tabA = new BroadcastChannel("cart");
const tabB = new BroadcastChannel("cart");
const log = [];
const both = Promise.all([tabA, tabB].map((channel, i) => new Promise((resolve) => {
channel.onmessage = (event) => { log.push(`${i ? "B" : "A"} got ${JSON.stringify(event.data)}`); resolve(); };
})));
sender.postMessage({ type: "item-added", sku: "oolong" });
await both;
console.log(log.sort().join("\n"));
for (const channel of [sender, tabA, tabB]) channel.close();
}
main();
A got {"type":"item-added","sku":"oolong"}
B got {"type":"item-added","sku":"oolong"}
The sending channel doesn't receive its own message. In a browser, each tab would create one BroadcastChannel("cart") and both post and listen on it.
Other kinds of workers
- A SharedWorker is a single worker shared by all same-origin tabs. Pages connect to it through
worker.port, which is useful for sharing one WebSocket connection between tabs. (Support in mobile browsers is limited.) - A service worker sits between your pages and the network. It intercepts
fetchrequests to serve cached responses offline, receives push notifications, and keeps working when no page is open. It's the foundation of Progressive Web Apps, and it uses the same messaging and Cache APIs (article 119). - Worklets (audio worklets, paint worklets) are lightweight scripts that run inside the browser's rendering or audio pipeline.
When to use a worker
Use workers for CPU-heavy work that would block the page for more than a frame or two: parsing large files, image and video processing, compression, cryptography, search indexing, simulations and WebAssembly computations. They don't help with network waits (fetch is already asynchronous), and the cost of copying data back and forth means tiny tasks are better kept on the main thread. For long main-thread work that must touch the DOM, split it into chunks and yield between them, for example with await scheduler.yield() where supported (article 107).
Common questions
Can a worker update the DOM?
No. Workers have no document. Send the results to the main thread with postMessage and update the DOM there. For drawing, a worker can render into an OffscreenCanvas that the page transferred to it.
Why is my ArrayBuffer empty after posting it?
You listed it in the transfer list, so it moved to the receiver and is now detached (byteLength 0). Omit the transfer list to send a copy instead, or don't use the buffer after transferring it.
Why does my window message listener fire for messages I didn't expect?
Any window, including browser extensions and other frames, can post messages to yours. Check event.origin against an allow-list and validate event.data before acting on it.
Summary
new Worker(url, { type: "module" })runs a script on its own thread with its own global scope (self), event loop and memory. Workers havefetch, timers and IndexedDB, but no DOM.- Communication is by
postMessageandmessageevents. Data is structured-cloned; transferringArrayBuffers and ports moves them, detaching the sender's copy. MessageChannelcreates connected port pairs; tagging messages with IDs builds a promise-based RPC layer.SharedArrayBufferwithAtomicsprovides true shared memory, only on cross-origin isolated pages.- Window-to-window
postMessageneeds a specific target origin when sending and anevent.origincheck when receiving.BroadcastChannelreaches every same-origin tab. - SharedWorkers, service workers and worklets are specialized workers for shared connections, offline support and rendering pipelines.
Practice Questions
A worker posts { result, render: () => draw(result) } to the page. What happens?
Answer
postMessage throws a DataCloneError, because functions can't be structured-cloned. Send only data, and let the page decide how to render it.
After worker.postMessage(pixels.buffer, [pixels.buffer]), what is pixels.length in the page?
Answer
0. The buffer was transferred, so it's detached, and the typed array viewing it has length 0. The worker now owns the memory.
What two checks make this iframe message listener safe?
window.addEventListener("message", (e) => { document.body.innerHTML = e.data.html; });
Answer
Verify e.origin against the expected origin, and never insert received HTML with innerHTML (XSS). Validate the data's shape and insert text with textContent:
window.addEventListener("message", (e) => {
if (e.origin !== "https://trusted.example") return;
if (typeof e.data?.text === "string") status.textContent = e.data.text;
});
Why might moving a 5 ms computation into a worker make the page slower overall?
Answer
Starting a worker and copying data to and from it can cost more than 5 ms. Workers pay off for long or repeated heavy tasks, especially with a reused worker and transferred buffers.
Previous: Web Storage, Cookies and IndexedDB: Saving Data in the Browser
Next: Example: A Parallel Mandelbrot Explorer with Workers and Canvas, plus Other Browser APIs

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.