SharedWorker: SharedWorker() constructor

Baseline 2026 *
Newly available

Since May 2026, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

* Some parts of this feature may have varying levels of support.

Warning: The script passed to the url parameter is executed. APIs like this are known as injection sinks, and are potentially a vector for cross-site scripting (XSS) attacks.

You can mitigate this risk by having a Content Security Policy (CSP) that restricts the locations from which scripts can be loaded, and by always assigning TrustedScriptURL objects instead of strings and enforcing trusted types. See Security considerations in the Worker() constructor for more information.

The SharedWorker() constructor creates a SharedWorker object that executes the script at the specified URL.

Syntax

js
new SharedWorker(url)
new SharedWorker(url, name)
new SharedWorker(url, options)

Parameters

url

A TrustedScriptURL object or a string representing the URL of the script or module that the worker will execute. This must be same-origin with the caller's document, or a blob: or data: URL. The URL is resolved relative to the current HTML page's location.

name Optional

A string specifying an identifying name for the SharedWorkerGlobalScope representing the scope of the worker, which is useful for creating new instances of the same SharedWorker and debugging.

options Optional

An object containing option properties that can be set when creating the object instance. Available properties are as follows:

type

A string specifying the type of worker to create. The value can be classic or module. The default used is classic.

credentials

A string specifying whether the browser sends credentials when importing modules into a module worker. The allowed values are the same as can be passed to the fetch() request: omit, same-origin, or include. The default is same-origin (only include credentials for same-origin requests).

This is ignored for classic workers.

name

A string specifying an identifying name for the SharedWorkerGlobalScope representing the scope of the worker, which is mainly useful for debugging purposes.

extendedLifetime

A boolean indicating whether the shared worker is allowed to remain alive for a short period after all pages using it have been navigated away from or closed.

This is provided to allow work to be done after the user navigates away from the page, such as writing state information to storage, or sending analytics data back to servers. The exact time that the worker is kept alive depends on the browser, and could be anywhere between 10 seconds and 5 minutes (Chrome uses 30 seconds).

For more information see Shared worker lifetime in Using web workers.

sameSiteCookies

A string indicating which SameSite cookies should be available to the worker. Can have one of the following two values:

'all'

SameSite=Strict, SameSite=Lax, and SameSite=None cookies will all be available to the worker. This option is only supported in first-party contexts, and is the default in first-party contexts.

'none'

Only SameSite=None cookies will be available to the worker. This option is supported in first-party and third-party contexts, and is the default in third-party contexts.

Warning: Once a shared worker with a particular URL and name is running, the type, credentials, and extendedLifetime options are fixed. Constructing a new shared worker for the same script and name will error if you specify different values for these options. If different options are required for the same script, then start two workers with different name values.

Exceptions

SecurityError DOMException

Thrown if the document is not allowed to start workers, for example if the URL has an invalid syntax or if the same-origin policy is violated, or if the sameSiteCookies value is not supported in the given context.

NetworkError DOMException

Thrown if the MIME type of the worker script is incorrect. It should always be text/javascript (for historical reasons other JavaScript MIME types may be accepted).

SyntaxError DOMException

Thrown if url cannot be parsed.

TypeError

Thrown if the url parameter is a string when Trusted Types are enforced by a CSP and no default policy is defined.

Description

The SharedWorker() constructor creates a SharedWorker object that executes the classic script or module at the specified URL.

The script must be same-origin with the associated document, but may itself import scripts or modules that are cross-origin (if permitted by CORS and other restrictions). If a cross-origin worker is required, users must load it from an intermediate same-origin worker or a blob.

For more information see Description in the Worker() constructor.

Examples

For brevity, the following examples don't use Trusted Types. In production your code should always use trusted types when passing data originating from users into injection sinks.

For an example, see Using Trusted Types in the Worker() constructor examples.

Basic usage

The following code snippet shows creation of a SharedWorker object using the SharedWorker() constructor and subsequent usage of the object:

js
const myWorker = new SharedWorker("worker.js");

myWorker.port.start();

[first, second].forEach((input) => {
  input.onchange = () => {
    myWorker.port.postMessage([first.value, second.value]);
    console.log("Message posted to worker");
  };
});

myWorker.port.onmessage = (e) => {
  result1.textContent = e.data;
  console.log("Message received from worker");
};

For a full example, see our Basic shared worker example (run shared worker.)

Constructing an already running worker will reuse the existing worker

If you construct a new shared worker with the same options as an already running shared worker, it will reuse the existing shared worker.

js
const worker1 = new SharedWorker("./worker.js");

// This will reuse worker1 for worker2
const worker2 = new SharedWorker("./worker.js");

Constructing a shared worker with options

The following code snippet shows creation of a SharedWorker object using the SharedWorker() constructor with the extendedLifetime option.

js
const worker = new SharedWorker("worker.js", { extendedLifetime: true });

worker.addEventListener("error", (event) => {});

If supported, this shared worker will continue to live on for a short period after the user has navigated away from the page.

Shared workers with different options

This example shows how you can start shared workers with different constructor options, by giving each a unique name.

First we demonstrate what happens if you use the same script and name with different options. This code would log worker2 error on instantiation: to the console because one instance sets the extendedLifetime option and the other doesn't. The same thing would happen if we set different type or credentials values.

js
const worker = new SharedWorker("worker.js", { extendedLifetime: true });

// Construct the same shared worker with different options.
const worker2 = new SharedWorker("worker.js");

// Handle constructor errors
worker2.addEventListener("error", (event) => {
  console.log(`worker2 error on instantiation: ${event}`);
});

The following code creates a second worker from the same script, but with a different name and options. No error will be logged to the console as the shared workers are different.

js
const worker = new SharedWorker("worker.js", { extendedLifetime: true });

// Start a second instance of worker.js
const worker2 = new SharedWorker("./worker.js", {
  name: "worker2",
  credentials: "omit",
});

worker2.port.start();

Specifications

Specification
HTML
# dom-sharedworker-dev

Browser compatibility

See also