Back to Content

ServiceWorkerRegistration: update() method

files/en-us/web/api/serviceworkerregistration/update/index.md

latest1.6 KB
Original Source

{{APIRef("Service Workers API")}}{{SecureContext_Header}} {{AvailableInWorkers}}

The update() method of the {{domxref("ServiceWorkerRegistration")}} interface attempts to update the service worker. It fetches the worker's script URL, and if the new worker is not byte-by-byte identical to the current worker, it installs the new worker. The fetch of the worker bypasses any browser caches if the previous fetch occurred over 24 hours ago.

Syntax

js-nolint
update()

Parameters

None.

Return value

A {{jsxref("Promise")}} that resolves with a {{domxref("ServiceWorkerRegistration")}} object.

Examples

The following simple example registers a service worker example then adds an event handler to a button so you can explicitly update the service worker whenever desired:

js
if ("serviceWorker" in navigator) {
  navigator.serviceWorker
    .register("/sw.js", { scope: "/" })
    .then((registration) => {
      // registration worked
      console.log("Registration succeeded.");
      button.onclick = () => {
        registration.update();
      };
    })
    .catch((error) => {
      // registration failed
      console.error(`Registration failed with ${error}`);
    });
}

Specifications

{{Specifications}}

Browser compatibility

{{Compat}}

See also