ServiceWorkerContainer: register() method
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.
Secure context: This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
Note: This feature is available in Web Workers.
Warning:
The scriptURL parameter passed to this method represents the URL of an external script loaded into a service worker.
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 register() method of the ServiceWorkerContainer interface creates or updates a ServiceWorkerRegistration for the given scope.
Syntax
register(scriptURL)
register(scriptURL, options)
Parameters
scriptURL-
A
TrustedScriptURLinstance or a string defining the URL of the service worker script. The registered service worker file needs to be served with a valid JavaScript media type. optionsOptional-
An object containing registration options. Currently available options are:
scope-
A string representing a URL that defines a service worker's registration scope; that is, what range of URLs a service worker can control.
This is usually specified as a URL that is relative to the base URL of the site (e.g.,
/some/path/), so that the resolved scope is the same irrespective of what page the registration code is called from. The defaultscopefor a service worker registration is the directory where the service worker script is located (resolving./againstscriptURL).The scope should be used to specify documents that are in the same directory or more deeply nested than the service worker. If you need a broader scope, this can be permitted via the HTTP
Service-Worker-Allowedheader. See the Examples section for information on broadening the default scope of a service worker. type-
A string specifying the type of worker to create. Valid values are:
'classic'-
The loaded service worker is in a standard script. This is the default.
'module'-
The loaded service worker is in an ES module and the import statement is available on worker contexts. For ES module compatibility info, see the browser compatibility data table for the
ServiceWorkerinterface.
updateViaCache-
A string indicating how the HTTP cache is used for service worker scripts resources during updates. Note: This only refers to the service worker script and its imports, not other resources fetched by these scripts.
'all'-
The HTTP cache will be queried for the main script, and all imported scripts. If no fresh entry is found in the HTTP cache, then the scripts are fetched from the network.
'imports'-
The HTTP cache will be queried for imports, but the main script will always be updated from the network. If no fresh entry is found in the HTTP cache for the imports, they're fetched from the network.
'none'-
The HTTP cache will not be used for the main script or its imports. All service worker script resources will be updated from the network.
Return value
A Promise that resolves with a ServiceWorkerRegistration object.
Exceptions
TypeError-
The
scriptURLorscope URLis a failure. This can happen if the URL can't be resolved to a valid URL or uses a scheme that is nothttp:orhttps. It may also happen ifscriptURLis not aTrustedScriptURL, and this is a requirement of the site's Trusted Types Policy.The exception is also raised if the
scriptURLorscope URLpath contains the case-insensitive ASCII "%2f" (*) or "%5c" (=) SecurityErrorDOMException-
The
scriptURLis not a potentially trustworthy origin, such aslocalhostor anhttpsURL. ThescriptURLand scope are not same-origin with the registering page.
Description
The register() method creates or updates a ServiceWorkerRegistration for the given scope.
If successful, the registration associates the provided script URL to a scope, which is subsequently used for matching documents to a specific service worker.
A single registration is created for each unique scope.
If register() is called for a scope that has an existing registration, the registration is updated with any changes to the scriptURL or options.
If there are no changes, then the existing registration is returned.
Calling register() with the same scope and scriptURL does not restart the installation process, so it is generally safe to call this method unconditionally from a controlled page.
However, it does send a network request for the service worker script, which may put more load on the server.
If this is a concern, you can first check for an existing registration using ServiceWorkerContainer.getRegistration().
A document can potentially be within the scope of several registrations with different service workers and options. The browser will associate the document with the matching registration that has the most specific scope. This ensures that only one service worker runs for each document.
Note: It is generally safer not to define registrations that have overlapping scopes.
Security considerations
The scriptURL parameter specifies the script for service worker, which can intercept network requests for pages within its scope and return respones that are fresh, cached, new, or modified.
If the input 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 script-src or 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 examples below should be read together to understand how service worker scope applies to a page.
Note that the first example shows how to use the method with trusted types. The other examples omit this step for brevity.
Using TrustedScriptURL
To mitigate the risk of XSS, we should always assign TrustedScriptURL instances to the scriptURL parameter.
We also need to do this if we're enforcing trusted types for other reasons and we want to allow some script sources that have been permitted (by CSP: worker-src).
Trusted types are not yet supported on all browsers, so first we define the trusted types tinyfill. This acts as a transparent replacement for the trusted types JavaScript API:
if (typeof trustedTypes === "undefined")
trustedTypes = { createPolicy: (n, rules) => rules };
Next we create a TrustedTypePolicy that defines a createScriptURL() method for transforming input strings into TrustedScriptURL instances.
For the purpose of this example we'll assume that we want to allow a predefined set of URLs in the scriptAllowList array and log any other scripts.
const scriptAllowList = [
// Some list of allowed URLs
];
const policy = trustedTypes.createPolicy("script-url-policy", {
createScriptURL(input) {
if (scriptAllowList.includes(input)) {
return input; // allow the script
}
console.log(`Script not in scriptAllowList: ${input}`);
return ""; // Block the script
},
});
Then we use the policy object to create a trustedScript object from a potentially unsafe input string:
// The potentially malicious string
// We won't be including untrustedScript in our scriptAllowList array
const untrustedScript = "https://evil.example.com/service_worker.js";
// Create a TrustedScriptURL instance using the policy
const trustedScriptURL = policy.createScriptURL(untrustedScript);
The trustedScriptURL property can now be used to register our service worker.
navigator.serviceWorker.register(trustedScriptURL).
Register a service worker with default scope
The following example uses the default value of scope by omitting it, which sets it to be the same location as the script URL.
Suppose the service worker code is at example.com/sw.js, and the registration code at example.com/index.html.
The service worker code will control example.com/index.html, as well as pages underneath it, like example.com/product/description.html.
if ("serviceWorker" in navigator) {
// Register a service worker hosted at the root of the
// site using the default scope.
navigator.serviceWorker.register("/sw.js").then(
(registration) => {
console.log("Service worker registration succeeded:", registration);
},
(error) => {
console.error(`Service worker registration failed: ${error}`);
},
);
} else {
console.error("Service workers are not supported.");
}
Note that we have registered the scriptURL relative to the site root rather than the current page.
This allows the same registration code to be used from any page.
Register a service worker with an explicit default scope
The code below is almost identical, except we have specified the scope explicitly using { scope: "/" }.
We've specified the scope as site-relative so the same registration code can be used from anywhere in the site.
if ("serviceWorker" in navigator) {
// declaring scope manually
navigator.serviceWorker.register("./sw.js", { scope: "/" }).then(
(registration) => {
console.log("Service worker registration succeeded:", registration);
},
(error) => {
console.error(`Service worker registration failed: ${error}`);
},
);
} else {
console.error("Service workers are not supported.");
}
This scope is the same as the default scope, so the registration applies to exactly the same pages as the previous example. Note that if we were to run this code after the previous example, browsers should recognize that we're updating an existing registration rather than a new one.
Register a service worker using page-relative URLs
There is nothing to stop you from using page-relative URLs except that this makes it harder to move your pages around, and it is easy to accidentally create unwanted registrations if you do so.
In this example the service worker code is at example.com/product/sw.js, and the registration code at example.com/product/description.html.
We're using URLs that are relative to the current directory for the scriptURL and the scope, where the current directory is the base URL of the page that is calling register() (example.com/product/).
The service worker applies to resources under example.com/product/.
if ("serviceWorker" in navigator) {
// declaring scope manually
navigator.serviceWorker.register("./sw.js", { scope: "./" }).then(
(registration) => {
console.log("Service worker registration succeeded:", registration);
},
(error) => {
console.error(`Service worker registration failed: ${error}`);
},
);
} else {
console.error("Service workers are not supported.");
}
Using Service-Worker-Allowed to increase service worker scope
A service worker can't have a scope broader than its own location, unless the server specifies a broader maximum scope in a Service-Worker-Allowed header on the service worker script.
Use the scope option when you need a narrower scope than the default.
The following code, if included in example.com/index.html, at the root of a site, would only apply to resources under example.com/product.
if ("serviceWorker" in navigator) {
// declaring scope manually
navigator.serviceWorker.register("./sw.js", { scope: "/product/" }).then(
(registration) => {
console.log("Service worker registration succeeded:", registration);
},
(error) => {
console.error(`Service worker registration failed: ${error}`);
},
);
} else {
console.error("Service workers are not supported.");
}
As noted above, servers can change the default scope by setting the Service-Worker-Allowed header on the service worker script.
This allows the scope option to be set outside the path defined by the service worker's location.
The following code, if included in example.com/product/index.html, would apply to all resources under example.com if the server set the Service-Worker-Allowed header to / or https://example.com/ when serving sw.js. If the server doesn't set the header, the service worker registration will fail, as the requested scope is too broad.
if ("serviceWorker" in navigator) {
// Declaring a broadened scope
navigator.serviceWorker.register("./sw.js", { scope: "/" }).then(
(registration) => {
// The registration succeeded because the Service-Worker-Allowed header
// had set a broadened maximum scope for the service worker script
console.log("Service worker registration succeeded:", registration);
},
(error) => {
// This happens if the Service-Worker-Allowed header doesn't broaden the scope
console.error(`Service worker registration failed: ${error}`);
},
);
} else {
console.error("Service workers are not supported.");
}
Specifications
| Specification |
|---|
| Service Workers Nightly> # navigator-service-worker-register> |