docs.rodeo

MDN Web Docs mirror

ServiceWorkerContainer

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

The ServiceWorkerContainer interface of the Service Worker API provides an object representing the service worker as an overall unit in the network ecosystem, including facilities to register, unregister and update service workers, and access the state of service workers and their registrations.

Most importantly, it exposes the {{domxref("ServiceWorkerContainer.register()")}}  method used to register service workers, and the {{domxref("ServiceWorkerContainer.controller")}}  property used to determine whether or not the current page is actively controlled.

ServiceWorkerContainer objects are exposed in the Window scope through {{domxref("Navigator.serviceWorker")}}  and in workers using {{domxref("WorkerNavigator.serviceWorker")}}  (if supported — check browser compatibility).

{{InheritanceDiagram}} 

Instance properties

Instance methods

Events

Examples

The example below first checks to see if the browser supports service workers. If supported, the code registers the service worker and determines if the page is actively controlled by the service worker. If it isn’t, it prompts the user to reload the page so the service worker can take control. The code also reports any registration failures.

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);

      // At this point, you can optionally do something
      // with registration. See https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
    })
    .catch((error) => {
      console.error(`Service worker registration failed: ${error}`);
    });

  // Independent of the registration, let's also display
  // information about whether the current page is controlled
  // by an existing service worker, and when that
  // controller changes.

  // First, do a one-off check if there's currently a
  // service worker in control.
  if (navigator.serviceWorker.controller) {
    console.log(
      "This page is currently controlled by:",
      navigator.serviceWorker.controller,
    );
  }

  // Then, register a handler to detect when a new or
  // updated service worker takes control.
  navigator.serviceWorker.oncontrollerchange = () => {
    console.log(
      "This page is now controlled by",
      navigator.serviceWorker.controller,
    );
  };
} else {
  console.log("Service workers are not supported.");
}

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN