Skip to content
AnswerWell geo Documentation

Research · 11 min read · Answerwell

Web Workers: Dedicated Worker, SharedWorker, MessagePort and Global Scope

How WHATWG HTML defines dedicated and shared workers, messaging with postMessage and MessagePort, structured cloning, and worker global scope APIs.

This page summarises the WHATWG HTML specification’s Web workers chapter, related structured-clone messaging rules, and the parts of web messaging that matter when pages and workers talk to each other.

Web workers: what runs off the main thread

Section titled “Web workers: what runs off the main thread”

A web worker is a separate JavaScript global environment that runs in the background while the page keeps its own event loop. The page does not block on worker computation, but the worker cannot touch the DOM; communication is message-based.

The global scope is the “inside” of a worker.

— WHATWG, 10 Web workers

All worker globals inherit from WorkerGlobalScope. The kinds this page covers are DedicatedWorkerGlobalScope (one page connection per Worker instance) and SharedWorkerGlobalScope (one script, many clients via connect). ServiceWorkerGlobalScope is named in the same hierarchy but is not described here.

Aspect Worker (dedicated) SharedWorker
Who connects One owning document (or worker) Many documents or workers on the same origin
Page-side API worker.onmessage, worker.postMessage sharedWorker.port.onmessage, sharedWorker.port.postMessage
End from the page worker.terminate() No terminate() on the interface; call close() inside the worker global
Identity New global per construction Reused by script URL, optional name, and origin
Typical use Heavy work for one page Shared state or connections across tabs

For simple same-origin tab notifications (for example logout sync), the spec steers authors toward BroadcastChannel; for elaborate shared state or a shared connection to a server, SharedWorker is the better fit.

For elaborate cases, e.g. to manage locking of shared state, to manage synchronization of resources between a server and multiple local clients, to share a WebSocket connection with a remote host, and so forth, shared workers are the most appropriate solution.

For simple cases, though, where a shared worker would be an unreasonable overhead, authors can use the simple channel-based broadcast mechanism described in this section.

— WHATWG, Broadcasting to other browsing contexts (cross-reference to BroadcastChannel)

Dedicated workers: Worker constructor and lifecycle

Section titled “Dedicated workers: Worker constructor and lifecycle”
worker = new Worker(scriptURL [, options ])

Returns a new Worker object. scriptURL will be fetched and executed in the background, creating a new global environment for which worker represents the communication channel.

— WHATWG, Worker interface

WorkerOptions include:

  • name — debugging label; exposed as DedicatedWorkerGlobalScope.name.
  • type — "classic" (default) or "module".
  • credentials — fetch credentials for the script only when type is "module" (default "same-origin").

Script URL rules:

Any same-origin URL (including blob: URLs) can be used. data: URLs can also be used, but they create a worker with an opaque origin.

— WHATWG, Worker constructor

An invalid URL throws a SyntaxError DOMException.

How postMessage works with a dedicated worker

Section titled “How postMessage works with a dedicated worker”

Dedicated workers use MessagePort objects behind the scenes, and thus support all the same features, such as sending structured data, transferring binary data, and transferring other ports.

— WHATWG, Communicating with a dedicated worker

On the page, use worker.onmessage or addEventListener('message', ...). Inside the worker, use onmessage and postMessage.

The implicit MessagePort used by dedicated workers has its port message queue implicitly enabled when it is created, so there is no equivalent to the MessagePort interface’s start() method on the Worker interface.

— WHATWG, Communicating with a dedicated worker

Transfer large buffers without copying:

worker.postMessage({
operation: 'find-edges',
input: buffer,
threshold: 0.6,
}, [buffer]);

From the page, worker.terminate() aborts the worker’s global environment. Inside the worker, close() on DedicatedWorkerGlobalScope aborts the dedicated worker global and discards queued tasks.

Classic workers load extra scripts with importScripts(...urls):

Fetches each URL in urls, executes them one-by-one in the order they are passed, and then returns (or throws if something went amiss).

— WHATWG, WorkerGlobalScope/importScripts

Module workers (type: "module") use the module graph instead; do not rely on importScripts there.

Shared workers: identity, port, and connect

Section titled “Shared workers: identity, port, and connect”

Shared workers use slightly different APIs, since each worker can have multiple connections.

— WHATWG, Shared workers introduction

Shared workers are identified by the URL of the script used to create it, optionally with an explicit name. The name allows multiple instances of a particular shared worker to be started.

Shared workers are scoped by origin. Two different sites using the same names will not collide. However, if a page tries to use the same shared worker name as another page on the same site, but with a different script URL, it will fail.

— WHATWG, Shared workers

Construct with new SharedWorker(scriptURL), new SharedWorker(scriptURL, name), or new SharedWorker(scriptURL, options).

Why you use worker.port instead of worker.onmessage

Section titled “Why you use worker.port instead of worker.onmessage”

Communicating with shared workers is done with explicit MessagePort objects. The object returned by the SharedWorker() constructor holds a reference to the port on its port attribute.

— WHATWG, Shared workers

Returns sharedWorker’s MessagePort object which can be used to communicate with the global environment.

— WHATWG, SharedWorker/port

On the page:

worker.port.onmessage = function (event) { /* ... */ };
worker.port.postMessage('some message');

Inside the worker, new clients arrive via connect:

Inside the shared worker, new clients of the worker are announced using the connect event. The port for the new client is given by the event object’s source attribute.

— WHATWG, Shared workers

onconnect = function (event) {
var newPort = event.source; // examples also use event.ports[0]
newPort.onmessage = function (event) { /* ... */ };
newPort.postMessage('ready!');
};

When you must call port.start() on a MessagePort

Section titled “When you must call port.start() on a MessagePort”

For MessagePort objects (including sharedWorker.port), the port message queue starts disabled. Setting onmessage the first time enables it, as if start() had been called. If you only use addEventListener('message', ...), call port.start() yourself.

The start() method steps are to enable this’s port message queue, if it is not already enabled.

— WHATWG, Message ports

The first time a MessagePort object’s onmessage IDL attribute is set, the port’s port message queue must be enabled, as if the start() method had been called.

— WHATWG, Message ports

Dedicated Worker instances hide this; shared workers and raw MessageChannel ports do not.

extendedLifetime and matching an existing shared worker

Section titled “extendedLifetime and matching an existing shared worker”

SharedWorkerOptions extend WorkerOptions with extendedLifetime (boolean, default false) so the worker can finish async work shortly after all owners disappear.

Note that attempting to construct a shared worker with options whose type, credentials, or extendedLifetime values mismatch those of an existing shared worker with the same constructor URL and name, will cause the returned sharedWorker to fire an error event and not connect to the existing shared worker.

— WHATWG, SharedWorker interface

A secure-context mismatch between caller and worker also fires error on the SharedWorker and aborts the connection. There is no page-side terminate() for SharedWorker; only SharedWorkerGlobalScope.close() inside the worker ends the shared global.

For DedicatedWorkerGlobalScope instances, it is simply a developer-supplied name, useful mostly for debugging purposes. For SharedWorkerGlobalScope instances, it allows obtaining a reference to a common shared worker via the SharedWorker() constructor.

— WHATWG, WorkerGlobalScope name

Worker global scope: location, navigator, and shared APIs

Section titled “Worker global scope: location, navigator, and shared APIs”

Inside any worker, self is the global object. location is a read-only WorkerLocation (like Location but without assign(), replace(), reload(), or ancestorOrigins). navigator is a WorkerNavigator subset: client identification, languages, on-line state, and hardware concurrency.

The WorkerLocation interface is like the Location interface, but lacks the assign(), replace(), reload(), and ancestorOrigins members.

— WHATWG, WorkerLocation

navigator.hardwareConcurrency returns the number of logical processors potentially available to the user agent (or 1 if unknown).

Workers and windows both mix in WindowOrWorkerGlobalScope: among other APIs, origin, isSecureContext, crossOriginIsolated, timers, queueMicrotask, structuredClone, and btoa/atob. For security-sensitive origin checks, the developer edition prefers self.origin over location.origin.

Developers are strongly encouraged to use self.origin over location.origin.

— WHATWG, WindowOrWorkerGlobalScope

Event handlers on WorkerGlobalScope include onerror, onunhandledrejection, onrejectionhandled, ononline, and onoffline; support for network on-line events in workers varies by browser.

Structured clone and transferable objects in worker messages

Section titled “Structured clone and transferable objects in worker messages”

Worker and port messages use the structured clone algorithm (the same family as structuredClone() on WorkerGlobalScope).

Serializable objects support being serialized, and later deserialized, in a way that is independent of any given realm. This allows them to be stored on disk and later restored, or cloned across agent and even agent cluster boundaries.

— WHATWG, Serializable objects

Wait - I used wrong URL. Should be https://html.spec.whatwg.org/multipage/structured-data.html

Takes the input value and returns a deep copy by performing the structured clone algorithm. Transferable objects listed in the transfer array are transferred, not just cloned, meaning that they are no longer usable in the input value.

— WHATWG, Structured cloning API

After you list an ArrayBuffer in the transfer array of postMessage, the sender must treat it as detached. Non-serializable values throw DataCloneError.

MessageEvent (used for worker message events, ports, and cross-document messaging) exposes data, origin, source, and ports.

Messages in server-sent events, cross-document messaging, channel messaging, broadcast channels, and WebSockets use the MessageEvent interface for their message events

— WHATWG, The MessageEvent interface

Cross-document postMessage and workers (same messaging model)

Section titled “Cross-document postMessage and workers (same messaging model)”

Pages talking to iframes or opener windows use window.postMessage, not worker APIs, but the same structured data and port rules apply when you pass MessagePort instances.

While this is an important security feature, it prevents pages from different domains from communicating even when those pages are not hostile. This section introduces a messaging system that allows documents to communicate with each other regardless of their source domain, in a way designed to not enable cross-site scripting attacks.

— WHATWG, Cross-document messaging

Posts a message to the given window. Messages can be structured objects, e.g. nested objects and arrays, can contain JavaScript values (strings, numbers, Date objects, etc.), and can contain certain data objects such as File Blob, FileList, and ArrayBuffer objects.

— WHATWG, Posting messages

targetOrigin in the options defaults to "/", which restricts delivery to same-origin targets. Cross-origin targets need an explicit origin or "*" (wildcard increases exposure).

A target origin can be specified using the targetOrigin member of options. If not provided, it defaults to “/”. This default restricts the message to same-origin targets only.

— WHATWG, Posting messages

If the origin of the target window doesn’t match the given target origin, the message is discarded, to avoid information leakage. To send the message to the target regardless of origin, set the target origin to “*”.

— WHATWG, Posting messages

Always verify event.origin on receive. For a newly navigated iframe, follow the spec’s handshake pattern: let the child announce readiness before the parent sends data.

MessageChannel creates entangled port1 / port2 pairs useful for handing a dedicated pipe to a worker:

Each channel has two message ports. Data sent through one port is received by the other port, and vice versa.

— WHATWG, Message ports

Legacy document.domain relaxation is deprecated; cross-origin coordination should use postMessage() or MessageChannel.

Avoid using the document.domain setter. It undermines the security protections provided by the same-origin policy.

Instead, use postMessage() or MessageChannel objects to communicate across origins in a safe manner.

— WHATWG, Relaxing the same-origin restriction

new BroadcastChannel(name) broadcasts to other browsing contexts with the same origin and storage key. Call close() when finished; leaving many channels with listeners open can look like a memory leak.

Authors are strongly encouraged to explicitly close BroadcastChannel objects when they are no longer needed, so that they can be garbage collected.

— WHATWG, Broadcasting

Worklets (for example CSS Houdini) load module scripts into WorkletGlobalScope via worklet.addModule(). They are not a substitute for Worker / SharedWorker when you need general parallel JavaScript and a message port to the page.

The Worklet class provides the capability to add module scripts into its associated WorkletGlobalScopes.

— WHATWG, The Worklet class

Cloudflare Workers runtime: browser MessageChannel differences

Section titled “Cloudflare Workers runtime: browser MessageChannel differences”

In browser HTML, MessageChannel supports transfer lists and shipping ports to other globals. On Cloudflare Workers, the runtime documents a narrower implementation:

The Workers runtime provides a minimal implementation of the MessageChannel API that is currently limited to uses with a single Worker instance.

— Cloudflare, MessageChannel

Transfer lists are currently not supported. This means that you will not be able to transfer ownership of objects like ArrayBuffer or MessagePort between ports.

— Cloudflare, MessageChannel — Differences

Do not assume browser worker messaging behaviour when writing Workers MessageChannel code; see Cloudflare’s 2025 changelog for updates.

Common mistakes with web workers and ports

Section titled “Common mistakes with web workers and ports”
  1. Listening on sharedWorker.onmessage instead of sharedWorker.port.onmessage.
  2. Using addEventListener('message') on a MessagePort without port.start() (dedicated Worker is exempt).
  3. Calling terminate() on a SharedWorker (it does not exist).
  4. Reconnecting to a shared worker with mismatched type, credentials, or extendedLifetime — results in an error event, not a new worker.
  5. Same name on one origin but a different script URL — construction fails.
  6. Reusing an ArrayBuffer after transferring it in postMessage.
  7. Sending cross-origin window.postMessage without setting targetOrigin (default "/" drops the message).
  8. Using document.domain instead of postMessage / MessageChannel for cross-origin work.
  1. Create a minimal dedicated worker: post a string from the page, echo from onmessage, then call terminate() and confirm the worker disappears from the browser’s worker inspection UI (for example DevTools Application → Workers where available).

  2. Open two same-origin tabs that construct new SharedWorker('your-script.js') with the same URL and name; verify both receive incremented connection counts from onconnect and that messages flow through each client’s port.

  3. In a shared-worker page client, switch from onmessage to addEventListener('message') on worker.port and confirm whether you need worker.port.start() for delivery.

  4. Post an ArrayBuffer with a transfer list; after send, confirm the buffer’s byte length is zero in the sender and intact in the worker.

  5. Intentionally mismatch type or extendedLifetime when connecting to an existing shared worker name and confirm the SharedWorker object fires error instead of connecting.

You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact wording you are asking about.