Worker: Worker() constructor
Baseline
Widely available
*
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
* Some parts of this feature may have varying levels of support.
Note: This feature is available in Web Workers, except for Service Workers.
Warning:
This script passed to the url element 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 for more information.
The Worker() constructor creates a Worker object that executes the script at the specified URL.
This script must obey the same-origin policy.
Syntax
new Worker(url)
new Worker(url, options)
Parameters
url-
A
TrustedScriptURLobject or a string representing the URL of the script the worker will execute. It must obey the same-origin policy. The URL is resolved relative to the current HTML page's location. optionsOptional-
An object containing option properties that can be set when creating the object instance. Available properties are as follows:
credentials-
A string specifying the type of credentials to use for the worker. The value can be
omit,same-origin, orinclude. If not specified, or if type isclassic, the default used issame-origin(only include credentials for same-origin requests). name-
A string specifying an identifying name for the
DedicatedWorkerGlobalScoperepresenting the scope of the worker, which is mainly useful for debugging purposes. type-
A string specifying the type of worker to create. The value can be
classicormodule. If not specified, the default used isclassic.
Exceptions
NetworkErrorDOMException-
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). SecurityErrorDOMException-
Thrown if the document is not allowed to start workers, e.g., if the URL has an invalid syntax or if the same-origin policy is violated.
SyntaxErrorDOMException-
Thrown if
urlcannot be parsed. TypeError-
Thrown if the
urlparameter is set with a string when Trusted Types are enforced by a CSP and no default policy is defined.
Description
>data: and blob: URLs
data: urls can be passed to the url parameter, but have an opaque_origin, which makes them cross-origin to all other origins including their owner.
Consequently, while the worker can still communicate with its owner using postMessage(), it's access to other external resources is highly restricted.
For example, a worker fetch() request would be cross-origin to its own site, and any requests to any origin must be granted by CORS.
blob: urls should be used instead, where possible, because the URL inherits the origin of the document that created it.
This ensures that a worker created with a blob: URL is same-origin with the page that created it.
Bundler considerations
Bundlers such as webpack, Vite, and Parcel, recommend passing URLs that are relative to import.meta.url to the Worker() constructor.
For example:
const myWorker = new Worker(new URL("worker.js", import.meta.url));
This makes the path relative to the current script instead of the current HTML page, which allows the bundler to safely do optimizations like renaming (because otherwise the worker.js URL may point to a file not controlled by the bundler, so it cannot make any assumptions.
Security considerations
The script specified by the url argument is executed in the context of the current page.
If the url is provided by a user, this is a possible vector for cross-site scripting (XSS) attacks.
It is extremely risky to accept and execute arbitrary URLs from untrusted origins.
A website should control what scripts that are allowed to run using a Content Security Policy (CSP) with the worker-src directive (or a fallback defined in default-src).
This can restrict scripts to those from the current origin, or a specific set of origins, or even particular files.
If you're using this property and enforcing trusted types (using the require-trusted-types-for CSP directive), you will need to always assign TrustedScriptURL objects instead of strings.
This ensures that the input is passed through a transformation function, which has the chance to reject or modify the URL before it is injected.
Examples
The following code snippet shows creation of a Worker object using the Worker() constructor and subsequent usage of the object:
const myWorker = new Worker("worker.js");
const first = document.querySelector("input#number1");
first.onchange = () => {
myWorker.postMessage(first.value);
console.log("Message posted to worker");
};
For a full example, see our Basic dedicated worker example (run dedicated worker).
Specifications
| Specification |
|---|
| HTML> # dom-worker-dev> |