Service Workers Nightly

Editor’s Draft,

More details about this document
This version:
https://w3c.github.io/ServiceWorker/
Latest published version:
https://www.w3.org/TR/service-workers/
Implementation Report:
https://wpt.fyi/results/service-workers
Test Suite:
https://github.com/web-platform-tests/wpt/tree/master/service-workers
Feedback:
GitHub
Inline In Spec
Editors:
(Microsoft)
(Google)
Former Editors:
(Google)
(Google)
(Microsoft‚ represented Samsung until April 2018)
(Google)

Abstract

The core of this specification is a worker that wakes to receive events. This provides an event destination that can be used when other destinations would be inappropriate, or no other destination exists.

For example, to allow the developer to decide how a page should be fetched, an event needs to dispatch potentially before any other execution contexts exist for that origin. To react to a push message, or completion of a persistent download, the context that originally registered interest may no longer exist. In these cases, the service worker is the ideal event destination.

This specification also provides a fetch event, and a request and response store similar in design to the HTTP cache, which makes it easier to build offline-enabled web applications.

Status of this document

This document was published by the Web Applications Working Group as an Editor’s Draft.

Publication as an Editor’s Draft does not imply endorsement by W3C and its Members.

This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than a work in progress.

This is a living document. Readers need to be aware that this specification may include unimplemented features, and details that may change. Service Workers 1 is a version that is advancing toward a W3C Recommendation.

This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent that the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

This document is governed by the 18 August 2025 W3C Process Document.

1. Motivations

This section is non-normative.

Web Applications traditionally assume that the network is reachable. This assumption pervades the platform. HTML documents are loaded over HTTP and traditionally fetch all of their sub-resources via subsequent HTTP requests. This places web content at a disadvantage versus other technology stacks.

The service worker is designed first to redress this balance by providing a Web Worker context, which can be started by a runtime when navigations are about to occur. This event-driven worker is registered against an origin and a path (or pattern), meaning it can be consulted when navigations occur to that location. Events that correspond to network requests are dispatched to the worker and the responses generated by the worker may override default network stack behavior. This puts the service worker, conceptually, between the network and a document renderer, allowing the service worker to provide content for documents, even while offline.

Web developers familiar with previous attempts to solve the offline problem have reported a deficit of flexibility in those solutions. As a result, the service worker is highly procedural, providing a maximum of flexibility at the price of additional complexity for developers. Part of this complexity arises from the need to keep service workers responsive in the face of a single-threaded execution model. As a result, APIs exposed by service workers are almost entirely asynchronous, a pattern familiar in other JavaScript contexts but accentuated here by the need to avoid blocking document and resource loading.

Developers using the HTML5 Application Cache have also reported that several attributes of the design contribute to unrecoverable errors. A key design principle of the service worker is that errors should always be recoverable. Many details of the update process of service workers are designed to avoid these hazards.

Service workers are started and kept alive by their relationship to events, not documents. This design borrows heavily from developer and vendor experience with shared workers and Chrome Background Pages. A key lesson from these systems is the necessity to time-limit the execution of background processing contexts, both to conserve resources and to ensure that background context loss and restart is top-of-mind for developers. As a result, service workers bear more than a passing resemblance to Chrome Event Pages, the successor to Background Pages. Service workers may be started by user agents without an attached document and may be killed by the user agent at nearly any time. Conceptually, service workers can be thought of as Shared Workers that can start, process events, and die without ever handling messages from documents. Developers are advised to keep in mind that service workers may be started and killed many times a second.

Service workers are generic, event-driven, time-limited script contexts that run at an origin. These properties make them natural endpoints for a range of runtime services that may outlive the context of a particular document, e.g. handling push notifications, background data synchronization, responding to resource requests from other origins, or receiving centralized updates to expensive-to-calculate data (e.g., geolocation or gyroscope).

2. Model

2.1. Service Worker

A service worker is a type of web worker. A service worker executes in the registering service worker client’s origin.

A service worker has an associated state, which is one of "parsed", "installing", "installed", "activating", "activated", and "redundant". It is initially "parsed".

A service worker has an associated script url (a URL).

A service worker has an associated type which is either "classic" or "module". Unless stated otherwise, it is "classic".

A service worker has an associated containing service worker registration (a service worker registration), which contains itself.

A service worker has an associated global object (a ServiceWorkerGlobalScope object or null).

A service worker has an associated script resource (a script), which represents its own script resource. It is initially set to null.

A script resource has an associated has ever been evaluated flag. It is initially unset.

A script resource has an associated policy container (a policy container). It is initially a new policy container.

A service worker has an associated script resource map which is an ordered map where the keys are URLs and the values are responses.

A service worker has an associated set of used scripts (a set) whose item is a URL. It is initially a new set.

Note: The set of used scripts is only used to prune unused resources from a new worker’s map after installation, that were populated based on the old worker’s map during the update check.

A service worker has an associated skip waiting flag. Unless stated otherwise it is unset.

A service worker has an associated classic scripts imported flag. It is initially unset.

A service worker has an associated set of event types to handle (a set) whose item is an event listener’s event type. It is initially a new set.

A service worker has an associated set of extended events (a set) whose item is an ExtendableEvent. It is initially a new set.

A service worker has an associated start status which can be null or a Completion. It is initially null.

A service worker has an associated all fetch listeners are empty flag. It is initially unset.

A service worker has an associated list of router rules (a list of RouterRules). It is initially an empty list.

A service worker is said to be running if its event loop is running.

A service worker has an associated [[service worker queue]] (a parallel queue).

2.1.1. Lifetime

The lifetime of a service worker is tied to the execution lifetime of events and not references held by service worker clients to the ServiceWorker object.

A user agent may terminate service workers at any time it:

  • Has no event to handle.

  • Detects abnormal operation: such as infinite loops and tasks exceeding imposed time limits (if any) while handling the events.

2.1.2. Events

The Service Workers specification defines service worker events (each of which is an event) that include (see the list):

2.2. Service Worker Timing

Service workers mark certain points in time that are later exposed by the navigation timing API and resource timing API.

A service worker timing info is a struct. It has the following items:

start time

A DOMHighResTimeStamp, initially 0.

fetch event dispatch time

A DOMHighResTimeStamp, initially 0.

worker router evaluation start

A DOMHighResTimeStamp, initially 0.

worker cache lookup start

A DOMHighResTimeStamp, initially 0.

worker matched router source

A DOMString, initially an empty string.

worker final router source

A DOMString, initially an empty string.

2.3. Service Worker Registration

A service worker registration is a tuple of a scope url, a storage key, and a set of service workers, an installing worker, a waiting worker, and an active worker. A user agent may enable many service worker registrations at a single origin so long as the scope url of the service worker registration differs. A service worker registration of an identical scope url when one already exists in the user agent causes the existing service worker registration to be replaced.

A service worker registration has an associated storage key (a storage key).

A service worker registration has an associated scope url (a URL).

A service worker registration has an associated installing worker (a service worker or null) whose state is "installing". It is initially set to null.

A service worker registration has an associated waiting worker (a service worker or null) whose state is "installed". It is initially set to null.

A service worker registration has an associated active worker (a service worker or null) whose state is either "activating" or "activated". It is initially set to null.

A service worker registration has an associated last update check time. It is initially set to null.

A service worker registration is said to be stale if the registration’s last update check time is non-null and the time difference in seconds calculated by the current time minus the registration’s last update check time is greater than 86400.

A service worker registration has an associated update via cache mode, which is "imports", "all", or "none". It is initially set to "imports".

A service worker registration has one or more task queues that back up the tasks from its active worker’s event loop’s corresponding task queues. (The target task sources for this back up operation are the handle fetch task source and the handle functional event task source.) The user agent dumps the active worker’s tasks to the service worker registration’s task queues when the active worker is terminated and re-queues those tasks to the active worker’s event loop’s corresponding task queues when the active worker spins off. Unlike the task queues owned by event loops, the service worker registration’s task queues are not processed by any event loops in and of itself.

A service worker registration has an associated NavigationPreloadManager object.

A service worker registration has an associated navigation preload enabled flag. It is initially unset.

A service worker registration has an associated navigation preload header value, which is a byte sequence. It is initially set to `true`.

A service worker registration is said to be unregistered if registration map[this service worker registration’s (storage key, serialized scope url)] is not this service worker registration.

2.3.1. Lifetime

A user agent must persistently keep a list of registered service worker registrations unless otherwise they are explicitly unregistered. A user agent has a registration map that stores the entries of the tuple of service worker registration’s (storage key, serialized scope url) and the corresponding service worker registration. The lifetime of service worker registrations is beyond that of the ServiceWorkerRegistration objects which represent them within the lifetime of their corresponding service worker clients.

2.4. Service Worker Client

A service worker client is an environment.

A service worker client has an associated discarded flag. It is initially unset.

Each service worker client has the following environment discarding steps:

  1. Set client’s discarded flag.

Note: Implementations can discard clients whose discarded flag is set.

A service worker client has an algorithm defined as the origin that returns the service worker client’s origin if the service worker client is an environment settings object, and the service worker client’s creation URL’s origin otherwise.

A window client is a service worker client whose global object is a Window object.

A dedicated worker client is a service worker client whose global object is a DedicatedWorkerGlobalScope object.

A shared worker client is a service worker client whose global object is a SharedWorkerGlobalScope object.

A worker client is either a dedicated worker client or a shared worker client.

2.5. Control and Use

A service worker client has an active service worker that serves its own loading and its subresources. When a service worker client has a non-null active service worker, it is said to be controlled by that active service worker. When a service worker client is controlled by a service worker, it is said that the service worker client is using the service worker’s containing service worker registration. A service worker client’s active service worker is determined as explained in the following subsections.

The rest of the section is non-normative.

The behavior in this section is not fully specified yet and will be specified in HTML Standard. The work is tracked by the issue and the pull request.

2.5.1. The window client case

A window client is created when a browsing context is created and when it navigates.

When a window client is created in the process of a browsing context creation:

If the browsing context’s initial active document’s origin is an opaque origin, the window client’s active service worker is set to null. Otherwise, it is set to the creator document’s service worker client’s active service worker.

When a window client is created in the process of the browsing context’s navigation:

If the fetch is routed through HTTP fetch, the window client’s active service worker is set to the result of the service worker registration matching. Otherwise, if the created document’s origin is an opaque origin or not the same as its creator document’s origin, the window client’s active service worker is set to null. Otherwise, it is set to the creator document’s service worker client’s active service worker.

Note: For an initial replacement navigation, the initial window client that was created when the browsing context was created is reused, but the active service worker is determined by the same behavior as above.

Note: Sandboxed iframes without the sandboxing directives, allow-same-origin and allow-scripts, result in having the active service worker value of null as their origin is an opaque origin.

2.5.2. The worker client case

A worker client is created when the user agent runs a worker.

When the worker client is created:

When the fetch is routed through HTTP fetch, the worker client’s active service worker is set to the result of the service worker registration matching. Otherwise, if the worker client’s origin is an opaque origin, or the request’s URL is a blob URL and the worker client’s origin is not the same as the origin of the last item in the worker client’s global object’s owner set, the worker client’s active service worker is set to null. Otherwise, it is set to the active service worker of the environment settings object of the last item in the worker client’s global object’s owner set.

Note: Window clients and worker clients with a data: URL result in having the active service worker value of null as their origin is an opaque origin. Window clients and worker clients with a blob URL can inherit the active service worker of their creator document or owner, but if the request’s origin is not the same as the origin of their creator document or owner, the active service worker is set to null.

2.6. Task Sources

The following additional task sources are used by service workers.

The handle fetch task source

This task source is used for dispatching fetch events to service workers.

The handle functional event task source

This task source is used for features that dispatch other functional events, e.g. push events, to service workers.

Note: A user agent may use a separate task source for each functional event type in order to avoid a head-of-line blocking phenomenon for certain functional events.

2.7. User Agent Shutdown

A user agent must maintain the state of its stored service worker registrations across restarts with the following rules:

To attain this, the user agent must invoke Handle User Agent Shutdown when it terminates.

3. Client Context

Bootstrapping with a service worker:
// scope defaults to the path the script sits in
// "/" in this example
navigator.serviceWorker.register("/serviceworker.js").then(registration => {
  console.log("success!");
  if (registration.installing) {
    registration.installing.postMessage("Howdy from your installing page.");
  }
}, err => {
  console.error("Installing the worker failed!", err);
});

3.1. ServiceWorker

[SecureContext, Exposed=(Window,Worker)]
interface ServiceWorker : EventTarget {
  readonly attribute USVString scriptURL;
  readonly attribute ServiceWorkerState state;
  undefined postMessage(any message, sequence<object> transfer);
  undefined postMessage(any message, optional StructuredSerializeOptions options = {});

  // event
  attribute EventHandler onstatechange;
};
ServiceWorker includes AbstractWorker;

enum ServiceWorkerState {
  "parsed",
  "installing",
  "installed",
  "activating",
  "activated",
  "redundant"
};

A ServiceWorker object represents a service worker. Each ServiceWorker object is associated with a service worker. Multiple separate objects implementing the ServiceWorker interface across documents and workers can all be associated with the same service worker simultaneously.

A ServiceWorker object has an associated ServiceWorkerState object which is itself associated with service worker’s state.

3.1.1. Getting ServiceWorker instances

An environment settings object has a service worker object map, a map where the keys are service workers and the values are ServiceWorker objects.

To get the service worker object representing serviceWorker (a service worker) in environment (an environment settings object), run these steps:
  1. Let objectMap be environment’s service worker object map.

  2. If objectMap[serviceWorker] does not exist, then:

    1. Let serviceWorkerObj be a new ServiceWorker in environment’s Realm, and associate it with serviceWorker.

    2. Set serviceWorkerObj’s state to serviceWorker’s state.

    3. Set objectMap[serviceWorker] to serviceWorkerObj.

  3. Return objectMap[serviceWorker].

3.1.2. scriptURL

The scriptURL getter steps are to return the service worker’s serialized script url.

For example, consider a document created by a navigation to https://example.com/app.html which matches via the following registration call which has been previously executed:
// Script on the page https://example.com/app.html
navigator.serviceWorker.register("/service_worker.js");

The value of navigator.serviceWorker.controller.scriptURL will be "https://example.com/service_worker.js".

3.1.3. state

The state attribute must return the value (in ServiceWorkerState enumeration) to which it was last set.

3.1.4. postMessage(message, transfer)

The postMessage(message, transfer) method steps are:

  1. Let options be «[ "transfer" → transfer ]».

  2. Invoke postMessage(message, options) with message and options as the arguments.

3.1.5. postMessage(message, options)

The postMessage(message, options) method steps are:

  1. Let serviceWorker be the service worker represented by this.

  2. Let incumbentSettings be the incumbent settings object.

  3. Let incumbentGlobal be incumbentSettings’s global object.

  4. Let serializeWithTransferResult be StructuredSerializeWithTransfer(message, options["transfer"]). Rethrow any exceptions.

  5. If the result of running the Should Skip Event algorithm with "message" and serviceWorker is true, then return.

  6. Run these substeps in parallel:

    1. If the result of running the Run Service Worker algorithm with serviceWorker is failure, then return.

    2. Queue a task on the DOM manipulation task source to run the following steps:

      1. Let source be determined by switching on the type of incumbentGlobal:

        ServiceWorkerGlobalScope
        The result of getting the service worker object that represents incumbentGlobal’s service worker in the relevant settings object of serviceWorker’s global object.
        Window
        a new WindowClient object that represents incumbentGlobal’s relevant settings object.
        Otherwise
        a new Client object that represents incumbentGlobal’s associated worker
      2. Let origin be incumbentSettings’s origin.

      3. Let destination be the ServiceWorkerGlobalScope object associated with serviceWorker.

      4. Let deserializeRecord be StructuredDeserializeWithTransfer(serializeWithTransferResult, destination’s Realm).

        If this throws an exception, let e be the result of creating an event named messageerror, using ExtendableMessageEvent, with its origin initialized to origin and the source attribute initialized to source.

      5. Else:

        1. Let messageClone be deserializeRecord.[[Deserialized]].

        2. Let newPorts be a new frozen array consisting of all MessagePort objects in deserializeRecord.[[TransferredValues]], if any, maintaining their relative order.

        3. Let e be the result of creating an event named message, using ExtendableMessageEvent, with its origin initialized to origin, the source attribute initialized to source, the data attribute initialized to messageClone, and the ports attribute initialized to newPorts.

      6. Dispatch e at destination.

      7. Invoke Update Service Worker Extended Events Set with serviceWorker and e.

3.1.6. Event handler

The following is the event handler (and its corresponding event handler event type) that must be supported, as event handler IDL attributes, by all objects implementing ServiceWorker interface:

event handler event handler event type
onstatechange statechange

3.2.