files/en-us/web/api/serviceworkercontainer/register/index.md
{{APIRef("Service Workers API")}}{{SecureContext_Header}}{{AvailableInWorkers}}
[!WARNING] The
scriptURLparameter 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 {{domxref("TrustedScriptURL")}} objects instead of strings and enforcing trusted types. See Security considerations for more information.
The register() method of the {{domxref("ServiceWorkerContainer")}} interface creates or updates a {{domxref("ServiceWorkerRegistration")}} for the given scope.
register(scriptURL)
register(scriptURL, options)
scriptURL
options {{optional_inline}}
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 default scope for a service worker registration is the directory where the service worker script is located (resolving ./ against scriptURL).
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 {{HTTPHeader("Service-Worker-Allowed")}} header. See the Examples section for information on broadening the default scope of a service worker.
type
'classic'
'module'
ServiceWorker interface.updateViaCache
'all'
'imports'
'none'
A {{jsxref("Promise")}} that resolves with a {{domxref("ServiceWorkerRegistration")}} object.
TypeError
: The scriptURL or scope URL is a failure.
This can happen if the URL can't be resolved to a valid URL or uses a scheme that is not http: or https.
It may also happen if scriptURL is not a {{domxref("TrustedScriptURL")}}, and this is a requirement of the site's Trusted Types Policy.
The exception is also raised if the scriptURL or scope URL path contains the case-insensitive ASCII "%2f" (*) or "%5c" (=)
SecurityError {{domxref("DOMException")}}
scriptURL is not a potentially trustworthy origin, such as localhost or an https URL.
The scriptURL and scope are not same-origin with the registering page.The register() method creates or updates a {{domxref("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 {{domxref("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.
The scriptURL parameter specifies the script for the service worker, which can intercept network requests for pages within its scope and return responses 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 {{domxref("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.
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.
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 {{domxref("TrustedTypePolicy")}} that defines a {{domxref("TrustedTypePolicy/createScriptURL", "createScriptURL()")}} method for transforming input strings into {{domxref("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 TrustedScriptURL 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);
We can now pass the TrustedScriptURL object into register():
navigator.serviceWorker.register(trustedScriptURL);
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.
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.
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.");
}
A service worker can't have a scope broader than its own location, unless the server specifies a broader maximum scope in a {{HTTPHeader("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}}
{{Compat}}
unregister() method