Service Workers Nightly

Editor’s Draft,

This version:
https://slightlyoff.github.io/ServiceWorker/spec/service_worker/
Latest version:
https://www.w3.org/TR/service-workers/
Feedback:
public-webapps@w3.org with subject line “[service-workers] … message topic …” (archives)
Issue Tracking:
GitHub
Inline In Spec
Editors:
(Google)
(Samsung Electronics)
(Google)
(Google)

Abstract

This specification describes a method that enables applications to take advantage of persistent background processing, including hooks to enable bootstrapping of web applications while offline.

The core of this system is an event-driven Web Worker, which responds to events dispatched from documents and other sources. A system for managing installation, versions, and upgrades is provided.

The service worker is a generic entry point for event-driven background processing in the Web Platform that is extensible by other specifications.

Status of this document

This is a public copy of the editors’ draft. It is provided for discussion only and may change at any moment. Its publication here does not imply endorsement of its contents by W3C. Don’t cite this document other than as work in progress.

Changes to this document may be tracked at https://github.com/slightlyoff/ServiceWorker.

The (archived) public mailing list public-webapps@w3.org (see instructions) is preferred for discussion of this specification. When sending e-mail, please put the text “service-workers” in the subject, preferably like this: “[service-workers] …summary of comment…

This document was produced by the Web Platform Working Group.

This document was produced by a group operating under the 5 February 2004 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 which 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 1 September 2015 W3C Process Document.

This is a living document addressing new features including foreign fetch and header-based installation, etc. Readers need to be aware that this specification includes unstable features. Implementers interested in implementing this specification should refer to the latest TR of Service Workers 1 instead.

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#dfn-service-workerReferenced in:1. Motivations (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13) (14)2.1. Service Worker (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13) (14)2.1.1. Lifetime (2)2.2. Service Worker Registration (2) (3) (4)2.5. Task Sources (2) (3)2.6. User Agent Shutdown3.1. ServiceWorker (2) (3) (4)3.1.1. scriptURL3.1.3. postMessage(message, transfer)3.2.1. installing3.2.2. waiting3.2.3. active3.4. ServiceWorkerContainer3.4.1. controller3.5. ServiceWorkerMessageEvent (2)3.5.2. event.origin3.5.4. event.source3.6. Events (2) (3)4.1. ServiceWorkerGlobalScope (2) (3) (4)4.1.3. skipWaiting() (2) (3) (4)4.4. ExtendableEvent (2)4.4.1. event.waitUntil(f) (2) (3) (4) (5)4.5.1. event.registerForeignFetch(options) (2)4.6. FetchEvent (2)4.7. ForeignFetchEvent (2)4.8. ExtendableMessageEvent (2)5.2. Understanding Cache Lifetimes (2)6.1. Secure Context (2) (3) (4) (5)6.2. Content Security Policy6.3.1. Origin restriction (2) (3)6.4. Cross-Origin Resources and CORS6.5. Implementer Concerns (2) (3)6.6. Privacy (2)7. Storage Considerations (2)8. Extensibility8.4. Request Functional Event DispatchUpdateInstall (2)Run Service WorkerTerminate Service WorkerHandle FetchHandle Foreign FetchUpdate Registration StateUpdate Worker State (2) (3) (4) (5) (6) (7) (8) (9) (10)Match Service Worker for Foreign FetchGet Newest WorkerService Worker Script Request (2)Service Worker Script ResponseSyntax 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#dfn-stateReferenced in:2.2. Service Worker Registration (2) (3)3.1. ServiceWorker3.2.5. update()4.1.3. skipWaiting()4.4.1. event.waitUntil(f) (2) (3)Handle Fetch (2)Handle Foreign Fetch (2)Handle Functional Event (2)Update Worker State (2) (3), which is one of parsed, installing, installed, activating, activated, and redundant. It is initially parsed.

A service worker has an associated script url#dfn-script-urlReferenced in:3.1.1. scriptURL3.2.5. update()RegisterUpdate (2) (3)Soft UpdateRun Service Worker (2) (3) (a URL).

A service worker has an associated type#dfn-typeReferenced in:3.2.5. update()UpdateSoft UpdateRun Service Worker which is either "classic" or "module". Unless stated otherwise, it is "classic".

A service worker has an associated containing service worker registration#dfn-containing-service-worker-registrationReferenced in:2.1. Service Worker2.4. Selection and Use3.2.6. unregister()4.1.2. registration4.1.3. skipWaiting() (2) (3)4.3.4. claim()4.5.1. event.registerForeignFetch(options)4.9. Events (2)InstallRun Service WorkerTerminate Service WorkerHandle Fetch (2) (a service worker registration), which contains itself.

A service worker has an associated id#dfn-service-worker-idReferenced in:Update (an opaque string), which uniquely identifies itself during the lifetime of its containing service worker registration.

A service worker is dispatched a set of lifecycle events#dfn-lifecycle-eventsReferenced in:4.4. ExtendableEvent4.9. Events (2), install and activate, and functional events#dfn-functional-eventsReferenced in:2.5. Task Sources4.4.1. event.waitUntil(f)4.6. FetchEvent4.7. ForeignFetchEvent4.9. Events (2)8.2. Define Functional Event8.3. Define Event Handler8.4. Request Functional Event Dispatch (2) (3)Update Worker State (2) including fetch.

A service worker has an associated script resource#dfn-script-resourceReferenced in:2.1. Service Worker (2)6.2. Content Security Policy (2)Update (2)Run Service Worker (2)Service Worker Script Request (2)Service Worker Script ResponseSyntax (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#dfn-has-ever-been-evaluated-flagReferenced in:Run Service Worker (2). It is initially unset. A script resource has an associated HTTPS state#dfn-https-stateReferenced in:Run Service Worker which is "none", "deprecated", or "modern". Unless stated otherwise, it is "none".

A service worker has an associated script resource map#dfn-script-resource-mapReferenced in:6.3.2. importScripts(urls) (2) (3)6.6. Privacy which is a List of the Record {[[key]], [[value]]} where [[key]] is a URL and [[value]] is a script resource.

A service worker has an associated skip waiting flag#dfn-skip-waiting-flagReferenced in:3.6. Events4.1.3. skipWaiting()Install (2) (3). Unless stated otherwise it is unset.

A service worker has an associated imported scripts updated flag#dfn-imported-scripts-updated-flagReferenced in:6.3.2. importScripts(urls) (2)Install. It is initially unset.

A service worker has an associated set of event types to handle#dfn-set-of-event-types-to-handleReferenced in:Run Service WorkerHandle FetchHandle Functional Event whose element type is an event listener’s event type. It is initially set to null.

A service worker has an associated list of foreign fetch scopes#dfn-foreign-fetch-scopesReferenced in:4.5.1. event.registerForeignFetch(options)Match Service Worker for Foreign Fetch whose element type is a URL. It is initially empty.

A service worker has an associated list of foreign fetch origins#dfn-foreign-fetch-originsReferenced in:4.5.1. event.registerForeignFetch(options)Handle Foreign Fetch (2) whose element type is a URL. It is initially empty.

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.2. Service Worker Registration

A service worker registration#dfn-service-worker-registrationReferenced in:2.1. Service Worker2.2. Service Worker Registration (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13) (14)2.2.1. Lifetime (2) (3) (4)2.4. Selection and Use (2) (3) (4) (5) (6) (7) (8)2.6. User Agent Shutdown (2) (3)3.2. ServiceWorkerRegistration (2) (3)3.2.6. unregister() (2)3.4. ServiceWorkerContainer (2)3.4.2. ready3.4.3. register(scriptURL, options) (2)3.6. Events (2)6.1. Secure Context (2)6.6. Privacy8.1. Define API bound to Service Worker Registration8.4. Request Functional Event DispatchAppendix A: Algorithms (2) (3)Soft UpdateInstallActivateHandle Functional EventHandle Service Worker Client UnloadSet Registration (2)Clear RegistrationUpdate Registration StateMatch Service Worker RegistrationGet RegistrationGet Newest Worker is a tuple of a scope url 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 scope url#dfn-scope-urlReferenced in:2.2. Service Worker Registration (2) (3)2.2.1. Lifetime2.4. Selection and Use3.2.4. scope3.2.5. update()3.2.6. unregister()3.4.3. register(scriptURL, options) (2)4.5.1. event.registerForeignFetch(options)Appendix A: Algorithms (2)UpdateSoft UpdateInstallActivateSet RegistrationClear RegistrationService Worker Script Response (a URL).

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

A service worker registration has an associated installing worker#dfn-installing-workerReferenced in:2.2. Service Worker Registration2.6. User Agent Shutdown (2)3.6. Events4.4.1. event.waitUntil(f)4.9. EventsInstall (2) (3) (4) (5) (6)Handle User Agent Shutdown (2)Clear Registration (2)Update Registration State (2) (3)Update Worker State (2)Get Newest Worker (2) (a service worker or null) whose state is installing. It is initially set to null.

A service worker registration has an associated waiting worker#dfn-waiting-workerReferenced in:2.2. Service Worker Registration2.6. User Agent Shutdown4.1.3. skipWaiting()4.4.1. event.waitUntil(f) (2)Install (2) (3) (4) (5) (6)Activate (2)Handle Service Worker Client UnloadHandle User Agent ShutdownClear Registration (2)Update Registration State (2) (3)Update Worker StateGet Newest Worker (2) (a service worker or null) whose state is installed. It is initially set to null.

A service worker registration has an associated active worker#dfn-active-workerReferenced in:2.2. Service Worker Registration (2) (3) (4) (5) (6)2.3. Service Worker Client2.4. Selection and Use (2) (3)2.6. User Agent Shutdown3.4.2. ready (2) (3)3.6. Events4.1.3. skipWaiting()4.3.4. claim() (2) (3)4.4.1. event.waitUntil(f)4.9. EventsRegisterActivate (2) (3) (4) (5) (6) (7)Run Service WorkerHandle Fetch (2) (3)Handle Functional Event (2)Clear Registration (2)Update Registration State (2) (3)Update Worker State (2) (3)Match Service Worker for Foreign FetchGet Newest Worker (2) (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#dfn-last-update-check-timeReferenced in:Update (2) (3)Handle Fetch (2) (3)Handle Functional Event. It is initially set to null.

A service worker registration has an associated uninstalling flag#dfn-uninstalling-flagReferenced in:RegisterUpdateHandle Service Worker Client UnloadUnregister (2)Match Service Worker Registration. It is initially unset.

A service worker registration has one or more task queues#dfn-service-worker-registration-task-queueReferenced in:2.2. Service Worker Registration (2)Run Service WorkerTerminate Service Worker 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.

2.2.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 scope to registration map that stores the entries of the tuple of service worker registration’s 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.3. Service Worker Client

A service worker client#dfn-service-worker-clientReferenced in:2.1. Service Worker2.1.1. Lifetime2.2.1. Lifetime2.3. Service Worker Client (2) (3) (4) (5) (6)2.4. Selection and Use (2) (3) (4) (5) (6) (7) (8) (9)3.2.6. unregister() (2)3.4. ServiceWorkerContainer3.6. Events (2)4.1. ServiceWorkerGlobalScope4.2. Client4.3.1. get(id)4.3.2. matchAll(options) (2)4.3.4. claim()4.8.2. event.origin6.1. Secure Context (2)6.3.1. Origin restrictionAppendix A: AlgorithmsCreate JobInstall (2)Activate (2)Run Service WorkerHandle Fetch (2)Handle Service Worker Client Unload (2) (3)UnregisterNotify Controller ChangeCreate ClientCreate Window Client is a type of environment settings object.

A service worker client has an associated active worker#dfn-service-worker-client-active-workerReferenced in:3.2.6. unregister()3.4.1. controller3.6. Events4.2.8. navigate(url)4.3.2. matchAll(options)Handle Fetch (2) (3) (4) (an active worker) which currently controls it. It is initially set to null.

A service worker client has an associated id#dfn-service-worker-client-idReferenced in:4.2.3. id4.3.1. get(id)Handle Fetch (an opaque string), which uniquely identifies itself during its lifetime. It is initially set to a new unique value when the corresponding environment settings object that it represents is created.

A service worker client has an associated frame type#dfn-service-worker-client-frame-typeReferenced in:4.2.2. frameType, which is one of auxiliary, top-level, nested, and none. Unless stated otherwise it is none.

A window client#dfn-window-clientReferenced in:4.2.2. frameType (2) (3)4.3.1. get(id)4.3.2. matchAll(options) (2) (3)ActivateHandle Fetch is a service worker client whose global object is a Window object.

A dedicated worker client#dfn-dedicatedworker-clientReferenced in:2.3. Service Worker Client4.3.2. matchAll(options) is a service worker client whose global object is a DedicatedWorkerGlobalScope object.

A shared worker client#dfn-sharedworker-clientReferenced in:2.3. Service Worker Client4.3.2. matchAll(options)Activate is a service worker client whose global object is a SharedWorkerGlobalScope object.

A worker client#dfn-worker-clientReferenced in:2.4. Selection and Use is either a dedicated worker client or a shared worker client.

2.4. Selection and Use

A service worker client independently selects and uses a service worker registration for its own loading and its subresources. The selection#dfn-service-worker-registration-selectionReferenced in:2.4. Selection and Use (2) (3) of a service worker registration, upon a non-subresource request, is a process of either matching a service worker registration from scope to registration map or inheriting an existing service worker registration from its parent or owner context depending on the request’s url.

When the request’s url is not local, a service worker client matches a service worker registration from scope to registration map. That is, the service worker client attempts to consult a service worker registration whose scope url matches its creation url.

When the request’s url is local, if the service worker client’s responsible browsing context is a nested browsing context or the service worker client is a worker client, the service worker client inherits the service worker registration from its parent browsing context’s environment or one of the worker’s Documents' environment, respectively, if it exists.

If the selection was successful, the selected service worker registration’s active worker starts to control#dfn-controlReferenced in:2.3. Service Worker Client2.4. Selection and Use3.2.6. unregister()3.6. EventsService Worker Script Response the service worker client. Otherwise, the flow returns to fetch where it falls back to the default behavior. When a service worker client is controlled by an active worker, it is considered that the service worker client is using#dfn-useReferenced in:2.4. Selection and Use3.6. Events4.1.3. skipWaiting()InstallActivateHandle FetchHandle Service Worker Client Unload (2)Unregister the active worker’s containing service worker registration.

2.5. Task Sources

The following additional task sources are used by service workers.

The handle fetch task source#dfn-handle-fetch-task-sourceReferenced in:2.2. Service Worker RegistrationTerminate Service Worker (2)Handle FetchHandle Foreign Fetch
This task source is used for dispatching fetch events to service workers.
The handle functional event task source#dfn-handle-functional-event-task-sourceReferenced in:2.2. Service Worker RegistrationTerminate Service Worker (2)Handle Functional Event
This task source is used for features that dispatch other functional events, e.g. push events, to service workers.

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. For instance, a user agent may use a different task source for task events from other task sources.

2.6. 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 ServiceWorker:
// scope defaults to the path the script sits in
// "/" in this example
navigator.serviceWorker.register("/serviceworker.js").then(
  function(registration) {
    console.log("success!");
    if (registration.installing) {
      registration.installing.postMessage("Howdy from your installing page.");
    }
  },
  function(why) {
    console.error("Installing the worker failed!:", why);
  });

3.1. ServiceWorker

[Exposed=(Window,Worker)]
interface ServiceWorker : EventTarget {
  readonly attribute USVString scriptURL;
  readonly attribute ServiceWorkerState state;
  void postMessage(any message, optional sequence<Transferable> transfer);

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

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

A ServiceWorker#service-worker-interfaceReferenced in:2.1.1. Lifetime3.1. ServiceWorker (2) (3) (4) (5) (6)3.1.3. postMessage(message, transfer)3.1.4. Event handler3.2. ServiceWorkerRegistration (2) (3)3.2.1. installing3.2.2. waiting3.2.3. active3.4. ServiceWorkerContainer3.4.1. controller (2)3.5. ServiceWorkerMessageEvent (2) (3)3.5.4. event.source3.6. Events (2)4.1. ServiceWorkerGlobalScope4.2.4. postMessage(message, transfer)4.8. ExtendableMessageEvent (2)Update Registration State (2) (3)Update Worker State 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. scriptURL

The scriptURL#service-worker-url-attributeReferenced in:3.1. ServiceWorker3.1.1. scriptURL attribute must 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", { scope: "/" });

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

3.1.2. state

The state#service-worker-state-attributeReferenced in:3.1. ServiceWorker3.1.2. state3.1.3. postMessage(message, transfer)3.6. EventsUpdate Worker State attribute must return the value (in ServiceWorkerState#service-worker-state-enumReferenced in:3.1. ServiceWorker (2) (3)Update Worker State enumeration) to which it was last set.

3.1.3. postMessage(message, transfer)

The postMessage(message, transfer)#service-worker-postmessage-methodReferenced in:3.1. ServiceWorker3.1.3. postMessage(message, transfer) method must run these steps or their equivalent:

  1. If the state attribute value of the context object is "redundant", throw an "InvalidStateError" exception and abort these steps.
  2. Let newPorts be an empty array.
  3. Let transferMap be an empty association list of Transferable objects to placeholder objects.
  4. If the method was invoked with a second argument transfer, run these substeps:
    1. If any object is listed in transfer more than once, or any of the Transferable objects listed in transfer are marked as neutered, then throw a "DataCloneError" exception and abort these steps.
    2. For each object x in transfer in turn, add a mapping from x to a new unique placeholder object created for x to transferMap, and if x is a MessagePort object, also append the placeholder object to newPorts.
  5. Let clonedMessage be a structured clone of message with transferMap as the transferMap. If this throws an exception, rethrow that exception and abort these steps.
  6. Let serviceWorker be the service worker represented by the context object.
  7. Invoke Run Service Worker algorithm with serviceWorker as the argument.
  8. Let destination be the ServiceWorkerGlobalScope object associated with serviceWorker.
  9. If the method was invoked with a second argument transfer, run these substeps:
    1. Let newOwner be the destination’s environment settings object.
    2. For each object x in transfer in turn, obtain a new object y by transferring the object x to newOwner, and replace the placeholder object that was created for the object x by the new object y wherever the placeholder exists (i.e. in clonedMessage and in newPorts).
  10. Make newPorts into a read only array.
  11. Queue a task that runs the following steps:
    1. Create an event e that uses the ExtendableMessageEvent interface, with the event type message, which does not bubble, is not cancelable, and has no default action.
    2. Let the data attribute of e be initialized to clonedMessage.
    3. Let the origin attribute of e be initialized to the Unicode serialisation of the origin specified by the incumbent settings object.
    4. If the global object globalObject specified by the incumbent settings object is a ServiceWorkerGlobalScope object, let the source attribute of e be initialized to a new ServiceWorker object that represents globalObject’s service worker.
    5. Else if globalObject is a Window object, let the source attribute of e be initialized to a new WindowClient object that represents globalObject’s browsing context.
    6. Else, let it be initialized to a new Client object that represents the worker associated with globalObject.
    7. Let the ports attribute of e be initialized to newPorts.
    8. Dispatch e at destination.

    The task must use the DOM manipulation task source.

3.1.4. 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#service-worker-onstatechange-attributeReferenced in:3.1. ServiceWorker statechange

3.2. ServiceWorkerRegistration

[Exposed=(Window,Worker)]
interface ServiceWorkerRegistration : EventTarget {
  [Unforgeable] readonly attribute ServiceWorker? installing;
  [Unforgeable] readonly attribute ServiceWorker? waiting;
  [Unforgeable] readonly attribute ServiceWorker? active;

  readonly attribute USVString scope;

  [NewObject] Promise<void> update();
  [NewObject] Promise<boolean> unregister();

  // event
  attribute EventHandler onupdatefound;
};

A ServiceWorkerRegistration#service-worker-registration-interfaceReferenced in:2.2.1. Lifetime3.2. ServiceWorkerRegistration (2) (3) (4)3.2.7. Event handler3.4. ServiceWorkerContainer (2) (3)3.4.2. ready3.4.4. getRegistration(clientURL)3.4.5. getRegistrations()3.6. Events4.1. ServiceWorkerGlobalScope4.1.2. registration8.1. Define API bound to Service Worker RegistrationRegisterUpdateInstall (2)Update Registration State object represents a service worker registration. Each ServiceWorkerRegistration object is associated with a service worker registration#dfn-service-worker-registration-interface-service-worker-registrationReferenced in:3.2.4. scope3.2.5. update()3.2.6. unregister()3.6. Events (a service worker registration). Multiple separate objects implementing the ServiceWorkerRegistration interface across documents and workers can all be associated with the same service worker registration simultaneously.

installing#service-worker-registration-installing-attributeReferenced in:3.2. ServiceWorkerRegistration3.2.1. installingUpdate Registration State attribute must return the value to which it was last set.

The ServiceWorker objects returned from this attribute getter that represent the same service worker are the same objects.

waiting#service-worker-registration-waiting-attributeReferenced in:3.2. ServiceWorkerRegistration3.2.2. waitingUpdate Registration State attribute must return the value to which it was last set.

The ServiceWorker objects returned from this attribute getter that represent the same service worker are the same objects.

active#service-worker-registration-active-attributeReferenced in:3.2. ServiceWorkerRegistration3.2.3. activeUpdate Registration State attribute must return the value to which it was last set.

The ServiceWorker objects returned from this attribute getter that represent the same service worker are the same objects.

3.2.4. scope

The scope#service-worker-registration-scope-attributeReferenced in:3.2. ServiceWorkerRegistration3.2.4. scope attribute must return service worker registration’s serialized scope url.

In the example in section 3.1.1, the value of registration.scope, obtained from navigator.serviceWorker.ready.then(function(registration) { console.log(registration.scope); }) for example, will be "https://example.com/".

3.2.5. update()

update()#service-worker-registration-update-methodReferenced in:3.2. ServiceWorkerRegistration3.2.5. update() method must run these steps or their equivalent:

  1. Let p be a promise.
  2. Let registration be the service worker registration.
  3. Let newestWorker be the result of running Get Newest Worker algorithm passing registration as its argument.
  4. If newestWorker is null, reject p with an "InvalidStateError" exception and abort these steps.
  5. If the context object’s relevant settings object’s global object globalObject is a ServiceWorkerGlobalScope object, and globalObject’s associated service worker’s state is installing, reject p with an "InvalidStateError" exception and abort these steps.
  6. Let job be the result of running Create Job with update, registration’s scope url, newestWorker’s script url, p, and the context object’s relevant settings object client.
  7. Set job’s worker type to newestWorker’s type.
  8. Invoke Schedule Job with job.
  9. Return p.

The unregister() method unregisters the service worker registration. It is important to note that the currently controlled service worker client’s active worker’s containing service worker registration is effective until all the service worker clients (including itself) using this service worker registration unload. That is, the unregister() method only affects subsequent navigations.

unregister()#service-worker-registration-unregister-methodReferenced in:3.2. ServiceWorkerRegistration3.2.6. unregister() (2) (3) method must return the result of running these steps or their equivalent:

  1. Let p be a promise.
  2. Let job be the result of running Create Job with unregister, the scope url of the service worker registration, null, p, and the context object’s relevant settings object client.
  3. Invoke Schedule Job with job.
  4. Return p.

3.2.7. 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 ServiceWorkerRegistration interface:

event handler event handler event type
onupdatefound#service-worker-registration-onupdatefound-attributeReferenced in:3.2. ServiceWorkerRegistration updatefound
partial interface Navigator {
  [SecureContext, SameObject] readonly attribute ServiceWorkerContainer serviceWorker;
};

partial interface WorkerNavigator {
  [SecureContext, SameObject] readonly attribute ServiceWorkerContainer serviceWorker;
};

The serviceWorker#navigator-service-worker-attributeReferenced in:3.3. navigator.serviceWorker (2) (3) attribute must return the ServiceWorkerContainer object that is associated with the context object.

3.4. ServiceWorkerContainer

[SecureContext, Exposed=(Window,Worker)]
interface ServiceWorkerContainer : EventTarget {
  [Unforgeable] readonly attribute ServiceWorker? controller;
  [SameObject] readonly attribute Promise<ServiceWorkerRegistration> ready;

  [NewObject] Promise<ServiceWorkerRegistration> register(USVString scriptURL, optional RegistrationOptions options);

  [NewObject] Promise<any> getRegistration(optional USVString clientURL = "");
  [NewObject] Promise<sequence<ServiceWorkerRegistration>> getRegistrations();


  // events
  attribute EventHandler oncontrollerchange;
  attribute EventHandler onerror;
  attribute EventHandler onmessage; // event.source of message events is ServiceWorker object
};
dictionary RegistrationOptions#dictdef-serviceworkercontainer-registrationoptionsReferenced in:3.4. ServiceWorkerContainer {
  USVString scope#dom-registrationoptions-scopeReferenced in:3.4.3. register(scriptURL, options) (2);
  WorkerType type#dom-registrationoptions-typeReferenced in:3.4.3. register(scriptURL, options) = "classic";
};

The user agent must create a ServiceWorkerContainer object when a Navigator object or a WorkerNavigator object is created and associate it with that object.

A ServiceWorkerContainer#service-worker-container-interfaceReferenced in:3.3. navigator.serviceWorker (2) (3)3.4. ServiceWorkerContainer (2) (3) (4) (5) (6)3.4.6. Event handlers3.6. Events4.2.4. postMessage(message, transfer) (2) (3)Notify Controller Change provides capabilities to register, unregister, and update the service worker registrations, and provides access to the state of the service worker registrations and their associated service workers.

A ServiceWorkerContainer has an associated service worker client#dfn-service-worker-container-interface-clientReferenced in:3.4.1. controller3.4.2. ready3.4.3. register(scriptURL, options)3.4.4. getRegistration(clientURL)3.4.5. getRegistrations()3.6. Events4.2.4. postMessage(message, transfer) (2) (3) (4)Notify Controller Change, which is a service worker client whose global object is associated with the Navigator object or the WorkerNavigator object that the ServiceWorkerContainer is retrieved from.

A ServiceWorkerContainer object has an associated ready promise#dfn-ready-promiseReferenced in:3.4.2. ready (2) (3) (4) (a promise). It is initially set to a new promise.

controller#service-worker-container-controller-attributeReferenced in:3.4. ServiceWorkerContainer3.4.1. controller (2)3.6. Events attribute must return the result of running these steps or their equivalent:

  1. Let client be the context object’s service worker client.
  2. Return the ServiceWorker object that represents client’s active worker.

navigator.serviceWorker.controller returns null if the request is a force refresh (shift+refresh). The ServiceWorker objects returned from this attribute getter that represent the same service worker are the same objects.

ready#service-worker-container-ready-attributeReferenced in:3.4. ServiceWorkerContainer3.4.2. ready (2) attribute must return the result of running these steps or their equivalent:

  1. If the context object’s ready promise is settled, return the context object’s ready promise.
  2. Let client be the context object’s service worker client.
  3. Let registration be null.
  4. Let clientURL be client’s creation url.
  5. Run the following substeps in parallel:
    1. CheckRegistration: If the result of running Match Service Worker Registration algorithm, or its equivalent, with clientURL as its argument is not null, then:
      1. Set registration to the result value.
    2. Else:
      1. Wait until scope to registration map has a new entry.
      2. Jump to the step labeled CheckRegistration.
    3. If registration’s active worker is null, wait until registration’s active worker changes.

      Implementers should consider this condition is met when the corresponding registration request gets to the step 6 of Activate algorithm.

    4. Resolve context object’s ready promise with the ServiceWorkerRegistration object which represents registration.
  6. Return context object’s ready promise.

When the ready attribute is accessed, the returned promise will never reject. Instead, it waits until the promise resolves with a service worker registration that has an active worker.

The register(scriptURL, options) method creates or updates a service worker registration for the given scope url. If successful, a service worker registration ties the provided scriptURL to a scope url, which is subsequently used for navigation matching.

register(scriptURL, options)#service-worker-container-register-methodReferenced in:3.4. ServiceWorkerContainer3.4.3. register(scriptURL, options) (2) method must run these steps or their equivalent:

  1. Let p be a promise.
  2. Let client be the context object’s service worker client.
  3. Let scriptURL be the result of parsing scriptURL with entry settings object’s API base URL.
  4. If scriptURL is failure, reject p with a TypeError and abort these steps.
  5. If scriptURL’s scheme is not one of "http" and "https", reject p with a TypeError and abort these steps.
  6. If any of the strings in scriptURL’s path contains either ASCII case-insensitive "%2f" or ASCII case-insensitive "%5c", reject p with a TypeError and abort these steps.
  7. Let scopeURL be null.
  8. If options.scope is not present, set scopeURL to the result of parsing a string "./" with scriptURL.

    The scope url for the registration is set to the location of the service worker script by default.

  9. Else, set scopeURL to the result of parsing options.scope with entry settings object’s API base URL.
  10. If scopeURL is failure, reject p with a TypeError and abort these steps.
  11. If scopeURL’s scheme is not one of "http" and "https", reject p with a TypeError and abort these steps.
  12. If any of the strings in scopeURL’s path contains either ASCII case-insensitive "%2f" or ASCII case-insensitive "%5c", reject p with a TypeError and abort these steps.
  13. Let job be the result of running Create Job with register, scopeURL, scriptURL, p, and client.
  14. Set job’s worker type to options.type.
  15. Invoke Schedule Job with job.
  16. Return p.

getRegistration(clientURL)#service-worker-container-getregistration-methodReferenced in:3.4. ServiceWorkerContainer3.4.4. getRegistration(clientURL) method must run these steps or their equivalent:

  1. Let client be the context object’s service worker client.
  2. Let clientURL be the result of parsing clientURL with entry settings object’s API base URL.
  3. If clientURL is failure, return a promise rejected with a TypeError.
  4. If the origin of clientURL is not client’s origin, return a promise rejected with a "SecurityError" exception.
  5. Let promise be a new promise.
  6. Run the following substeps in parallel:
    1. Let registration be the result of running Match Service Worker Registration algorithm, or its equivalent, with clientURL as its argument.
    2. If registration is not null, then:
      1. Resolve promise with the ServiceWorkerRegistration object which represents registration.
    3. Else:
      1. Resolve promise with undefined.
  7. Return promise.

getRegistrations()#service-worker-container-getregistrations-methodReferenced in:3.4. ServiceWorkerContainer3.4.5. getRegistrations() method must run these steps or their equivalent:

  1. Let client be the context object’s service worker client.
  2. Let promise be a new promise.
  3. Run the following substeps in parallel:
    1. Let array be an empty array.
    2. For each Record {[[key]], [[value]]} entry of scope to registration map:
      1. If the origin of the result of parsing entry.[[key]] is the same as client’s origin, add the ServiceWorkerRegistration object associated with entry.[[value]] to the array.
    3. Resolve promise with array.
  4. Return promise.

3.4.6. Event handlers

The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the ServiceWorkerContainer interface:

event handler event handler event type
oncontrollerchange#service-worker-container-oncontrollerchange-attributeReferenced in:3.4. ServiceWorkerContainer controllerchange
onerror#service-worker-container-onerror-attributeReferenced in:3.4. ServiceWorkerContainer error
onmessage#service-worker-container-onmessage-attributeReferenced in:3.4. ServiceWorkerContainer message

3.5. ServiceWorkerMessageEvent

[Constructor(DOMString type, optional ServiceWorkerMessageEventInit eventInitDict), Exposed=(Window,Worker)]
interface ServiceWorkerMessageEvent : Event {
  readonly attribute any data;
  readonly attribute DOMString origin;
  readonly attribute DOMString lastEventId;
  [SameObject] readonly attribute (ServiceWorker or MessagePort)? source;
  readonly attribute FrozenArray<MessagePort>? ports;
};
dictionary ServiceWorkerMessageEventInit#dictdef-serviceworkermessageevent-serviceworkermessageeventinitReferenced in:3.5. ServiceWorkerMessageEvent : EventInit {
  any data;
  DOMString origin;
  DOMString lastEventId;
  (ServiceWorker or MessagePort)? source;
  sequence<MessagePort>? ports;
};

Service workers define the message event that extends the message event defined in [HTML] to allow setting a ServiceWorker object as the source of the message. For the message event, service workers use the ServiceWorkerMessageEvent#serviceworkermessage-event-interfaceReferenced in:3.5. ServiceWorkerMessageEvent (2)3.6. Events4.2.4. postMessage(message, transfer) interface.

3.5.1. event.data

The data#serviceworkermessage-event-data-attributeReferenced in:3.5. ServiceWorkerMessageEvent3.5.1. event.data4.2.4. postMessage(message, transfer) attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to null. It represents the message being sent.

3.5.2. event.origin

The origin#serviceworkermessage-event-origin-attributeReferenced in:3.5. ServiceWorkerMessageEvent3.5.2. event.origin4.2.4. postMessage(message, transfer) attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to the empty string. It represents the origin of the service worker’s environment settings object from which the message is sent.

3.5.3. event.lastEventId

The lastEventId#serviceworkermessage-event-lasteventid-attributeReferenced in:3.5. ServiceWorkerMessageEvent3.5.3. event.lastEventId attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to the empty string.

3.5.4. event.source

The source#serviceworkermessage-event-source-attributeReferenced in:3.5. ServiceWorkerMessageEvent3.5.4. event.source4.2.4. postMessage(message, transfer) attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to null. It represents the ServiceWorker object whose associated service worker the message is sent from.

3.5.5. event.ports

The ports#serviceworkermessage-event-ports-attributeReferenced in:3.5. ServiceWorkerMessageEvent3.5.5. event.ports4.2.4. postMessage(message, transfer) attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to null. It represents the MessagePort array being sent, if any.

3.6. Events

The following event is dispatched on ServiceWorker object:

Event name Interface Dispatched when…
statechange#service-worker-statechange-eventReferenced in:3.1.4. Event handler Event The state attribute of the ServiceWorker object is changed.

The following event is dispatched on ServiceWorkerRegistration object:

Event name Interface Dispatched when…
updatefound#service-worker-registration-updatefound-eventReferenced in:3.2.7. Event handler Event The service worker registration’s installing worker changes. (See step 8 of the Install algorithm.)

The following events are dispatched on ServiceWorkerContainer object:

Event name Interface Dispatched when…
controllerchange#service-worker-container-controllerchange-eventReferenced in:3.4.6. Event handlers Event The service worker client’s active worker changes. (See step 9.2 of the Activate algorithm. The skip waiting flag of a service worker causes activation of the service worker registration to occur while service worker clients are using the service worker registration, navigator.serviceWorker.controller immediately reflects the active worker as the service worker that controls the service worker client.)
message#service-worker-container-message-eventReferenced in:3.4.6. Event handlers3.5. ServiceWorkerMessageEvent (2)4.2.4. postMessage(message, transfer) ServiceWorkerMessageEvent When it receives a message.
error#service-worker-container-error-eventReferenced in:3.4.6. Event handlers ErrorEvent Any error occurred from the associated service workers.

4. Execution Context

Serving Cached Resources:
// caching.js
this.addEventListener("install", function(e) {
  e.waitUntil(
    // Open a cache of resources.
    caches.open("shell-v1").then(function(cache) {
      // Begins the process of fetching them.
      // The coast is only clear when all the resources are ready.
      return cache.addAll([
        "/app.html",
        "/assets/v1/base.css",
        "/assets/v1/app.js",
        "/assets/v1/logo.png",
        "/assets/v1/intro_video.webm"
      ]);
    })
  );
});

this.addEventListener("fetch", function(e) {
  // No "fetch" events are dispatched to the service worker until it
  // successfully installs and activates.

  // All operations on caches are async, including matching URLs, so we use
  // promises heavily. e.respondWith() even takes promises to enable this:
  e.respondWith(
    caches.match(e.request).then(function(response) {
      return response || fetch(e.request);
    }).catch(function() {
      return caches.match("/fallback.html");
    })
  );
});

4.1. ServiceWorkerGlobalScope

[Global=(Worker,ServiceWorker), Exposed=ServiceWorker]
interface ServiceWorkerGlobalScope : WorkerGlobalScope {
  // A container for a list of Client objects that correspond to
  // browsing contexts (or shared workers) that are on the origin of this SW
  [SameObject] readonly attribute Clients clients;
  [SameObject] readonly attribute ServiceWorkerRegistration registration;

  [NewObject] Promise<void> skipWaiting();

  attribute EventHandler oninstall;
  attribute EventHandler onactivate;
  attribute EventHandler onfetch;
  attribute EventHandler onforeignfetch;

  // event
  attribute EventHandler onmessage; // event.source of the message events is Client object
};

A ServiceWorkerGlobalScope#service-worker-global-scope-interfaceReferenced in:3.1.3. postMessage(message, transfer) (2)3.2.5. update()4.1. ServiceWorkerGlobalScope (2) (3) (4)4.1.4. Event handlers4.3. Clients4.4.1. event.waitUntil(f)4.9. Events6.3.2. importScripts(urls)8.3. Define Event Handler8.4. Request Functional Event DispatchRun Service Worker object represents the global execution context of a service worker. A ServiceWorkerGlobalScope object has an associated service worker#dfn-service-worker-global-scope-service-workerReferenced in:3.1.3. postMessage(message, transfer)3.2.5. update()4.1.2. registration4.2.4. postMessage(message, transfer)4.2.8. navigate(url) (2)4.3.1. get(id)4.3.2. matchAll(options) (2)4.3.3. openWindow(url)4.3.4. claim() (2) (3) (4) (5)4.5.1. event.registerForeignFetch(options)4.9. Events (2) (3) (4)6.3.2. importScripts(urls)Run Service Worker (a service worker).

ServiceWorkerGlobalScope object provides generic, event-driven, time-limited script execution contexts that run at an origin. Once successfully registered, a service worker is started, kept alive and killed by their relationship to events, not service worker clients. Any type of synchronous requests must not be initiated inside of a service worker.

4.1.1. clients

clients#service-worker-global-scope-clients-attributeReferenced in:4.1. ServiceWorkerGlobalScope4.1.1. clients attribute must return the Clients object that is associated with the context object.

4.1.2. registration

The registration#service-worker-global-scope-scope-attributeReferenced in:4.1. ServiceWorkerGlobalScope4.1.2. registration attribute must return the ServiceWorkerRegistration object that represents the service worker’s containing service worker registration.

4.1.3. skipWaiting()

The skipWaiting() method allows this service worker to progress from the registration’s waiting position to active even while service worker clients are using the registration.

skipWaiting()#service-worker-global-scope-skipwaiting-methodReferenced in:4.1. ServiceWorkerGlobalScope4.1.3. skipWaiting() (2) method must run these steps or their equivalent:

  1. Let promise be a new promise.
  2. Run the following substeps in parallel:
    1. Set service worker’s skip waiting flag
    2. If service worker’s state is installed, then:
      1. Run Activate algorithm, or its equivalent, passing service worker’s registration as the argument.
    3. Resolve promise with undefined.
  3. Return promise.

4.1.4. Event handlers

The following are the event handlers (and their corresponding event handler event types) that must be supported, as event handler IDL attributes, by all objects implementing the ServiceWorkerGlobalScope interface:

event handler event handler event type
oninstall#service-worker-global-scope-oninstall-attributeReferenced in:4.1. ServiceWorkerGlobalScope4.4.1. event.waitUntil(f)Update Worker State install
onactivate#service-worker-global-scope-onactivate-attributeReferenced in:4.1. ServiceWorkerGlobalScope4.4.1. event.waitUntil(f)Update Worker State activate
onfetch#service-worker-global-scope-onfetch-attributeReferenced in:4.1. ServiceWorkerGlobalScope fetch
onforeignfetch#dom-serviceworkerglobalscope-onforeignfetchReferenced in:4.1. ServiceWorkerGlobalScope foreignfetch
onmessage#service-worker-global-scope-onmessage-attributeReferenced in:4.1. ServiceWorkerGlobalScope message

4.2. Client

[Exposed=ServiceWorker]
interface Client {
  readonly attribute USVString url;
  readonly attribute FrameType frameType;
  readonly attribute DOMString id;
  void postMessage(any message, optional sequence<Transferable> transfer);
};

[Exposed=ServiceWorker]
interface WindowClient : Client {
  readonly attribute VisibilityState visibilityState;
  readonly attribute boolean focused;
  [NewObject] Promise<WindowClient> focus();
  [NewObject] Promise<WindowClient> navigate(USVString url);
};

enum FrameType {
  "auxiliary",
  "top-level",
  "nested",
  "none"
};

A Client#client-interfaceReferenced in:3.1.3. postMessage(message, transfer)4.2. Client (2) (3)4.3. Clients4.8. ExtendableMessageEvent (2)4.8.4. event.sourceCreate Client (2) object has an associated service worker client#dfn-service-worker-client-clientReferenced in:4.2.1. url4.2.2. frameType4.2.3. id4.2.4. postMessage(message, transfer)4.2.7. focus() (2) (3)4.2.8. navigate(url) (2) (3)Create ClientCreate Window Client (a service worker client).

A WindowClient#window-client-interfaceReferenced in:3.1.3. postMessage(message, transfer)4.2. Client (2) (3) (4)4.3. ClientsCreate Window Client (2) object has an associated visibility state#dfn-service-worker-client-visibilitystateReferenced in:4.2.5. visibilityStateCreate Window Client, which is one of visibilityState attribute value.

A WindowClient object has an associated focus state#dfn-service-worker-client-focusstateReferenced in:4.2.6. focused4.2.7. focus()Create Window Client, which is either true or false (initially false).

4.2.1. url

The url#client-url-attributeReferenced in:4.2. Client4.2.1. url attribute must return the context object’s associated service worker client’s serialized creation url.

4.2.2. frameType

The frameType#client-frametype-attributeReferenced in:4.2. Client4.2.2. frameType attribute must return the value (in FrameType#contextframetype-enumReferenced in:4.2. Client (2) enumeration) corresponding to the first matching statement, switching on service worker client’s frame type:

auxiliary
"auxiliary"

The window client’s global object’s browsing context is an auxiliary browsing context.

top-level
"top-level"

The window client’s global object’s browsing context is a top-level browsing context.

nested
"nested"

The window client’s global object’s browsing context is a nested browsing context.

none
"none"

4.2.3. id

The id#client-id-attributeReferenced in:4.2. Client4.2.3. id attribute must return its associated service worker client’s id.

4.2.4. postMessage(message, transfer)

The postMessage(message, transfer)#client-postmessage-methodReferenced in:4.2. Client4.2.4. postMessage(message, transfer) method must run these steps or their equivalent:

  1. Let newPorts be an empty array.
  2. Let transferMap be an empty association list of Transferable objects to placeholder objects.
  3. If the method was invoked with a second argument transfer, run these substeps:
    1. If any object is listed in transfer more than once, or any of the Transferable objects listed in transfer are marked as neutered, then throw a "DataCloneError" exception and abort these steps.
    2. For each object x in transfer in turn, add a mapping from x to a new unique placeholder object created for x to transferMap, and if x is a MessagePort object, also append the placeholder object to newPorts.
  4. Let clonedMessage be a structured clone of message with transferMap as the transferMap. If this throws an exception, rethrow that exception and abort these steps.
  5. Let destination be the ServiceWorkerContainer object whose service worker client is the context object’s service worker client.
  6. If destination is null, throw an "InvalidStateError" exception.
  7. If the method was invoked with a second argument transfer, run these substeps:
    1. Let newOwner be the destination’s service worker client.
    2. For each object x in transfer in turn, obtain a new object y by transferring the object x to newOwner, and replace the placeholder object that was created for the object x by the new object y wherever the placeholder exists (i.e. in clonedMessage and in newPorts).
  8. Make newPorts into a read only array.
  9. Queue a task that runs the following steps:
    1. Create an event e that uses the ServiceWorkerMessageEvent interface, with the event type message, which does not bubble, is not cancelable, and has no default action.
    2. Let the data attribute of e be initialized to clonedMessage.
    3. Let the origin attribute of e be initialized to the Unicode serialisation of the origin specified by the incumbent settings object.
    4. Let the source attribute of e be initialized to a ServiceWorker object, which represents the service worker associated with the global object specified by the incumbent settings object.
    5. Let the ports attribute of e be initialized to newPorts.
    6. Dispatch e at destination.

    The task must use the DOM manipulation task source, and, for those where the event loop specified by the target ServiceWorkerContainer object’s service worker client is a browsing context event loop, must be associated with the responsible document specified by that target ServiceWorkerContainer object’s service worker client.

4.2.5. visibilityState

The visibilityState#client-visibilitystate-attributeReferenced in:4.2. Client4.2.5. visibilityState attribute must return the context object’s visibility state.

4.2.6. focused

The focused#client-focused-attributeReferenced in:4.2. Client4.2.6. focused attribute must return the context object’s focus state.

4.2.7. focus()

The focus()#client-focus-methodReferenced in:4.2. Client4.2.7. focus() method must run these steps or their equivalent:

  1. If this algorithm is not allowed to show a popup, return a promise rejected with an "InvalidAccessError" exception.
  2. Let promise be a new promise.
  3. Run these substeps in parallel:
    1. Let browsingContext be the context object’s associated service worker client’s global object’s browsing context.
    2. Let visibilityState be null.
    3. Let focusState be null.
    4. Queue a task task to run the following substeps on the context object’s associated service worker client’s responsible event loop using the user interaction task source:
      1. Run the focusing steps with browsingContext.
      2. Set visibilityState to browsingContext’s active document’s visibilityState attribute value.
      3. Set focusState to the result of running the has focus steps with browsingContext’s active document as the argument.
    5. Wait for task to have executed.
    6. Let windowClient be the result of running Create Window Client algorithm, or its equivalent, with the context object’s associated service worker client, visibilityState and focusState as the arguments.
    7. If windowClient’s focus state is true, resolve promise with windowClient.
    8. Else, reject promise with a TypeError.
  4. Return promise.

4.2.8. navigate(url)

The navigate()#client-navigate-methodReferenced in:4.2. Client4.2.8. navigate(url) method must run these steps or their equivalent:

  1. Let url be the result of parsing url with entry settings object’s API base URL.
  2. If url is failure, return a promise rejected with a TypeError.
  3. If url is about:blank, return a promise rejected with a TypeError.
  4. If the context object’s associated service worker client’s active worker is not the incumbent settings object’s global object’s service worker, return a promise rejected with a TypeError.
  5. Let promise be a new promise.
  6. Run these substeps in parallel:
    1. Let browsingContext be the context object’s associated service worker client’s global object’s browsing context.
    2. If browsingContext has discarded its Document, reject promise with a TypeError and abort these steps.
    3. Let navigateFailed to false.
    4. Let visibilityState be null.
    5. Let focusState be null.
    6. Queue a task task to run the following substeps on the context object’s associated service worker client’s responsible event loop using the user interaction task source:
      1. HandleNavigate: Navigate browsingContext to url with replacement enabled and exceptions enabled. The source browsing context must be browsingContext.
      2. If the algorithm steps invoked in the step labeled HandleNavigate throws an exception, set navigateFailed to true.
      3. Set visibilityState to browsingContext’s active document’s visibilityState attribute value.
      4. Set focusState to the result of running the has focus steps with browsingContext’s active document as the argument.
    7. Wait for task to have executed (including its asynchronous steps).
    8. If navigateFailed is true, reject promise with a TypeError and abort these steps.
    9. If browsingContext’s Window object’s environment settings object’s creation url’s origin is not the same as the service worker’s origin, then:
      1. Resolve promise with null.
      2. Abort these steps.
    10. Let windowClient be the result of running Create Window Client algorithm, or its equivalent, with browsingContext’s Window object’s environment settings object, visibilityState and focusState as the arguments.
    11. Resolve promise with windowClient.
  7. Return promise.

4.3. Clients

[Exposed=ServiceWorker]
interface Clients {
  // The objects returned will be new instances every time
  [NewObject] Promise<any> get(DOMString id);
  [NewObject] Promise<sequence<Client>> matchAll(optional ClientQueryOptions options);
  [NewObject] Promise<WindowClient?> openWindow(USVString url);
  [NewObject] Promise<void> claim();
};
dictionary ClientQueryOptions#dictdef-clients-clientqueryoptionsReferenced in:4.3. Clients {
  boolean includeUncontrolled#dom-clientqueryoptions-includeuncontrolledReferenced in:4.3.2. matchAll(options) = false;
  ClientType type#dom-clientqueryoptions-typeReferenced in:4.3.2. matchAll(options) (2) (3) (4) = "window";
};
enum ClientType#enumdef-clients-clienttypeReferenced in:4.3. Clients {
  "window",
  "worker",
  "sharedworker",
  "all"
};

The user agent must create a Clients#clients-interfaceReferenced in:4.1. ServiceWorkerGlobalScope4.1.1. clients4.3. Clients (2) object when a ServiceWorkerGlobalScope object is created and associate it with that object.

4.3.1. get(id)

The get(id)#clients-get-methodReferenced in:4.3. Clients4.3.1. get(id) method must run these steps or their equivalent:

  1. Let promise be a new promise.
  2. Run these substeps in parallel:
    1. For each service worker client client whose origin is the same as the associated service worker’s origin:
      1. If client’s id is id, then:
        1. If client is not a secure context, reject promise with a "SecurityError" exception and abort these steps.
        2. If client is a window client, then:
          1. Let browsingContext be client’s global object’s browsing context.
          2. Let visibilityState be null.
          3. Let focusState be null.
          4. Queue a task task to run the following substeps:
            1. Set visibilityState to browsingContext’s active document’s visibilityState attribute value.
            2. Set focusState to the result of running the has focus steps with browsingContext’s active document as the argument.
          5. Wait for task to have executed.
          6. Let windowClient be the result of running Create Window Client algorithm, or its equivalent, with client, visibilityState and focusState as the arguments.
          7. Resolve promise with windowClient and abort these steps.
        3. Else:
          1. Let clientObject be the result of running Create Client algorithm, or its equivalent, with client as the argument.
          2. Resolve promise with clientObject and abort these steps.
    2. Resolve promise with undefined.
  3. Return promise.

4.3.2. matchAll(options)

The matchAll(options)#clients-matchall-methodReferenced in:4.3. Clients4.3.2. matchAll(options) method must run these steps or their equivalent:

  1. Let promise be a new promise.
  2. Run these substeps in parallel:
    1. Let targetClients be an empty array.
    2. For each service worker client client whose origin is the same as the associated service worker’s origin:
      1. If client is not a secure context, continue to the next iteration of the loop.
      2. If options.includeUncontrolled is false, then:
        1. If client’s active worker is the associated service worker, add client to targetClients.
      3. Else:
        1. Add client to targetClients.
    3. Let matchedClients be an empty array.
    4. For each service worker client client in targetClients, in the most recently focused order for window clients:
      1. If options.type is "window", and client is a window client, then:
        1. Let browsingContext be client’s global object’s browsing context.
        2. Let visibilityState be null.
        3. Let focusState be null.
        4. Queue a task task to run the following substeps on client’s responsible event loop using the user interaction task source:
          1. Set visibilityState to browsingContext’s active document’s visibilityState attribute value.
          2. Set focusState to the result of running the has focus steps with browsingContext’s active document as the argument.
        5. Wait for task to have executed.

          Wait is a blocking wait, but implementers may run the iterations in parallel as long as the state is not broken.

        6. Let windowClient be the result of running Create Window Client algorithm, or its equivalent, with client, visibilityState and focusState as the arguments.
        7. Add windowClient to matchedClients.
      2. Else if options.type is "worker" and client is a dedicated worker client, or options.type is "sharedworker" and client is a shared worker client, then:
        1. Let clientObject be the result of running Create Client algorithm, or its equivalent, with client as the argument.
        2. Add clientObject to matchedClients.
      3. Else if options.type is "all", then:
        1. If client is a window client, then:
          1. Let browsingContext be client’s global object’s browsing context.
          2. Let visibilityState be null.
          3. Let focusState be null.
          4. Queue a task task to run the following substeps on client’s responsible event loop using the user interaction task source:
            1. Set visibilityState to browsingContext’s active document’s visibilityState attribute value.
            2. Set focusState to the result of running the has focus steps with browsingContext’s active document as the argument.
          5. Wait for task to have executed.

            Wait is a blocking wait, but implementers may run the iterations in parallel as long as the state is not broken.

          6. Let windowClient be the result of running Create Window Client algorithm, or its equivalent, with client, visibilityState and focusState as the arguments.
          7. Add windowClient to matchedClients.
        2. Else:
          1. Let clientObject be the result of running Create Client algorithm, or its equivalent, with client as the argument.
          2. Add clientObject to matchedClients.
    5. Resolve promise with matchedClients.
  3. Return promise.

4.3.3. openWindow(url)

The openWindow(url)#clients-openwindow-methodReferenced in:4.3. Clients4.3.3. openWindow(url) method must run these steps or their equivalent:

  1. Let url be the result of parsing url with entry settings object’s API base URL.
  2. If url is failure, return a promise rejected with a TypeError.
  3. If url is about:blank, return a promise rejected with a TypeError.
  4. If this algorithm is not allowed to show a popup, return a promise rejected with an "<InvalidAccessError" exception.
  5. Let promise be a new promise.
  6. Run these substeps in parallel:
    1. Let newContext be a new top-level browsing context.
    2. Let openWindowFailed to false.
    3. Let visibilityState be null.
    4. Let focusState be null.
    5. Queue a task task to run the following substeps on newContext’s Window object’s environment settings object’s responsible event loop using the user interaction task source:
      1. HandleNavigate: Navigate newContext to url, with exceptions enabled and replacement enabled.
      2. If the algorithm steps invoked in the step labeled HandleNavigate throws an exception, set openWindowFailed to true.
      3. Set visibilityState to newContext’s active document’s visibilityState attribute value.
      4. Set focusState to the result of running the has focus steps with newContext’s active document as the argument.
    6. Wait for task to have executed (including its asynchronous steps).
    7. If openWindowFailed is true, reject promise with a TypeError and abort these steps.
    8. If newContext’s Window object’s environment settings object’s creation url’s origin is not the same as the service worker’s origin, then:
      1. Resolve promise with null.
      2. Abort these steps.
    9. Let client be the result of running Create Window Client algorithm, or its equivalent, with newContext’s Window object’s environment settings object, visibilityState and focusState as the arguments.
    10. Resolve promise with client.
  7. Return promise.

4.3.4. claim()

The claim()#clients-claim-methodReferenced in:4.3. Clients4.3.4. claim() method must run these steps or their equivalent:

  1. If the service worker is not an active worker, return a promise rejected with an "InvalidStateError" exception.
  2. Let promise be a new promise.
  3. Run the following substeps in parallel:
    1. For each service worker client client whose origin is the same as the service worker’s origin:
      1. If client is not a secure context, continue to the next iteration of the loop.
      2. Let registration be the result of running Match Service Worker Registration algorithm passing client’s creation url as the argument.
      3. If registration is not the service worker’s containing service worker registration, continue to the next iteration of the loop.
      4. If client’s active worker is not the service worker, then:
        1. Invoke Handle Service Worker Client Unload with client as the argument.
        2. Set client’s active worker to service worker.
        3. Invoke Notify Controller Change algorithm with client as the argument.
    2. Resolve promise with undefined.
  4. Return promise.

4.4. ExtendableEvent

[Constructor(DOMString type, optional ExtendableEventInit eventInitDict), Exposed=ServiceWorker]
interface ExtendableEvent : Event {
  void waitUntil(Promise<any> f);
};
dictionary ExtendableEventInit#dictdef-extendableeventinitReferenced in:4.4. ExtendableEvent4.5. InstallEvent4.6. FetchEvent4.7. ForeignFetchEvent4.8. ExtendableMessageEvent : EventInit {
  // Defined for the forward compatibility across the derived events
};

An ExtendableEvent#extendable-event-interfaceReferenced in:4.4. ExtendableEvent (2) (3) (4)4.5. InstallEvent4.6. FetchEvent (2)4.7. ForeignFetchEvent (2)4.8. ExtendableMessageEvent (2)4.9. Events8.2. Define Functional EventActivate object has an associated extend lifetime promises#dfn-extend-lifetime-promisesReferenced in:4.4.1. event.waitUntil(f) (2) (3) (4)InstallActivate (an array of promises). It is initially set to null.

Service workers have two lifecycle events, install and activate. Service workers use the ExtendableEvent interface for activate event and install event.

Service worker extensions that define event handlers may also use or extend the ExtendableEvent interface.

4.4.1. event.waitUntil(f)

waitUntil(f) method extends the lifetime of the event.

waitUntil(f)#extendable-event-waituntil-methodReferenced in:4.4. ExtendableEvent4.4.1. event.waitUntil(f) (2) (3)4.8. ExtendableMessageEventUpdate Worker State (2) method must run these steps or their equivalent:

  1. If the dispatch flag is unset, then:
    1. Throw an "InvalidStateError" exception.
    2. Abort these steps.
  2. Add f to extend lifetime promises.

In the task task in which the steps of waitUntil(f) is running, the user agent must run these steps or their equivalent:

  1. Let extendLifetimePromises be an empty array.
  2. For each event listener invoked:
    1. Let eventObject be the first argument passed to this event listener.
    2. Append eventObject’s extend lifetime promises to extendLifetimePromises.
  3. Do not terminate the service worker whose responsible event loop is running task until waiting for all of extendLifetimePromises settles.

However, the user agent may impose a time limit to this lifetime extension.

Service workers and extensions that define event handlers may define their own behaviors, allowing the extend lifetime promises to suggest operation length, and the rejected state of any of the promise in extend lifetime promises to suggest operation failure.

Service workers define the following behaviors for install event and activate event:

4.5. InstallEvent

[Constructor(DOMString type, optional ExtendableEventInit eventInitDict), Exposed=ServiceWorker]
interface InstallEvent#installevent-installeventReferenced in:4.5. InstallEvent4.9. EventsInstall : ExtendableEvent {
  void registerForeignFetch(ForeignFetchOptions options);
};

dictionary ForeignFetchOptions#dictdef-installevent-foreignfetchoptionsReferenced in:4.5. InstallEvent {
  required sequence<USVString> scopes#dom-foreignfetchoptions-scopesReferenced in:4.5.1. event.registerForeignFetch(options) (2);
  required sequence<USVString> origins#dom-foreignfetchoptions-originsReferenced in:4.5.1. event.registerForeignFetch(options) (2);
};

4.5.1. event.registerForeignFetch(options)

registerForeignFetch(options) registers this service worker to handle foreign fetches from certain origins for certain sub scopes.

registerForeignFetch(options)#dom-installevent-registerforeignfetchReferenced in:4.5. InstallEvent4.5.1. event.registerForeignFetch(options) (2) method must run these steps or their equivalent:

  1. If the dispatch flag is unset, then:
    1. Throw an "InvalidStateError" exception.
    2. Abort these steps.
  2. If options.origins is empty throw a TypeError and abort these steps.
  3. Let originURLs be an empty list of URLs.
  4. If the value of options.origins is not a single string equal to a single U+002A ASTERISK character (*):
    1. For each origin in options.origins:
      1. If the value of origin is not an absolute URL, throw a TypeError and abort these steps.
      2. Add the result of parsing origin to originURLs.
  5. If options.scopes is empty throw a TypeError and abort these steps.
  6. Let scopeString be the incumbent settings object’s global object’s service worker’s containing service worker registration’s scope url, serialized.
  7. Let subScopeURLs be an empty list of URLs.
  8. For each subScope in options.scopes:
    1. Let subScopeURL be the result of parsing subScope with entry settings object’s API base URL.
    2. If subScopeURL is failure, throw a TypeError and abort these steps.
    3. Let subScopeString be the serialized subScopeURL.
    4. If subScopeString does not start with scopeString, throw a TypeError and abort these steps.
    5. Add subScopeURL to subScopeURLs.
  9. Set this service worker’s list of foreign fetch scopes to subScopeURLs.
  10. Set this service worker’s list of foreign fetch origins to originURLs.

4.6. FetchEvent

[Constructor(DOMString type, FetchEventInit eventInitDict), Exposed=ServiceWorker]
interface FetchEvent : ExtendableEvent {
  [SameObject] readonly attribute Request request;
  readonly attribute DOMString? clientId;
  readonly attribute boolean isReload;

  void respondWith(Promise<Response> r);
};
dictionary FetchEventInit#dictdef-fetchevent-fetcheventinitReferenced in:4.6. FetchEvent : ExtendableEventInit {
  required Request request;
  DOMString? clientId = null;
  boolean isReload = false;
};

Service workers have an essential functional event fetch. For fetch event, service workers use the FetchEvent#fetch-event-interfaceReferenced in:4.6. FetchEvent (2) (3)4.9. Events (2)Handle Fetch interface which extends the ExtendableEvent interface.

Each event using FetchEvent interface has an associated potential response#fetchevent-potential-responseReferenced in:4.6.4. event.respondWith(r)Handle Fetch (a response), initially set to null, and the following associated flags that are initially unset:

4.6.1. event.request

request#fetch-event-request-attributeReferenced in:4.6. FetchEvent4.6.1. event.requestHandle FetchHandle Foreign Fetch attribute must return the value it was initialized to.

4.6.2. event.clientId

clientId#fetch-event-clientid-attributeReferenced in:4.6. FetchEvent4.6.2. event.clientIdHandle Fetch attribute must return the value it was initialized to. When an event is created the attribute must be initialized to null.

4.6.3. event.isReload

isReload#fetch-event-isreload-attributeReferenced in:4.6. FetchEvent4.6.3. event.isReloadHandle Fetch attribute must return the value it was initialized to. When an event is created the attribute must be initialized to false.

Pressing the refresh button should be considered a reload while clicking a link and pressing the back button should not. The behavior of the Ctrl+l enter is left to the implementations of the user agents.

4.6.4. event.respondWith(r)

Developers can set the argument r with either a promise that resolves with a Response object or a Response object (which is automatically cast to a promise). Otherwise, a network error is returned to Fetch. Renderer-side security checks about tainting for cross-origin content are tied to the types of filtered responses defined in Fetch.

respondWith(r)#fetch-event-respondwith-methodReferenced in:4.6. FetchEvent4.6.4. event.respondWith(r)6.4. Cross-Origin Resources and CORS method must run these steps or their equivalent:

  1. If the dispatch flag is unset, then:
    1. Throw an "InvalidStateError" exception.
    2. Abort these steps.
  2. If the respond-with entered flag is set, then:
    1. Throw an "InvalidStateError" exception.
    2. Abort these steps.
  3. Set the stop propagation flag and stop immediate propagation flag.
  4. Set the respond-with entered flag.
  5. Set the wait to respond flag.
  6. Run the following substeps in parallel:
    1. Wait until r settles.
    2. If r rejected, then:
      1. Set the respond-with error flag.
    3. If r resolved with response, then:
      1. If response is a Response object, then:
        1. If response is disturbed or locked, then:
          1. Set the respond-with error flag.
        2. Else:
          1. Let potentialResponse be a copy of response’s associated response, except for its body.
          2. If response’s body is non-null, run these substeps:
            1. Set potentialResponse’s body to response’s body.
            2. Let dummyStream be an empty ReadableStream object.
            3. Set response’s body to a new body whose stream is dummyStream.
            4. Let reader be the result of getting a reader from dummyStream.
            5. Read all bytes from dummyStream with reader.

            These substeps are meant to produce the observable equivalent of "piping" response’s body’s stream into potentialResponse. That is, response is left with a body with a ReadableStream object that is disturbed and locked, while the data readable from potentialResponse’s body’s stream is now equal to what used to be response’s, if response’s original body is non-null.

            These substeps will be replaced by using pipe when the algorithm for pipeTo becomes stable.

          3. Set the potential response to potentialResponse.
      2. Else:
        1. Set the respond-with error flag.

        If the respond-with error flag is set, a network error is returned to Fetch through Handle Fetch algorithm. (See the step 21.1.) Otherwise, the value response is returned to Fetch through Handle Fetch algorithm. (See the step 22.1.)

    4. Unset the wait to respond flag.

4.7. ForeignFetchEvent

[Constructor(DOMString type, ForeignFetchEventInit eventInitDict), Exposed=ServiceWorker]
interface ForeignFetchEvent : ExtendableEvent {
  [SameObject] readonly attribute Request request;

  void respondWith(Promise<ForeignFetchResponse> r);
};

dictionary ForeignFetchEventInit#dictdef-foreignfetchevent-foreignfetcheventinitReferenced in:4.7. ForeignFetchEvent : ExtendableEventInit {
  required Request request;
};

dictionary ForeignFetchResponse#dictdef-foreignfetchevent-foreignfetchresponseReferenced in:4.7. ForeignFetchEvent4.7.2. event.respondWith(r) {
  required Response response#dom-foreignfetchresponse-responseReferenced in:4.7.2. event.respondWith(r) (2) (3) (4) (5);
  USVString origin#dom-foreignfetchresponse-originReferenced in:4.7.2. event.respondWith(r);
  sequence<ByteString> headers#dom-foreignfetchresponse-headersReferenced in:4.7.2. event.respondWith(r);
};

Service workers have a functional event foreignfetch. For foreignfetch events, service workers use the ForeignFetchEvent#foreignfetchevent-foreignfetcheventReferenced in:4.7. ForeignFetchEvent (2) (3)Handle Foreign Fetch interface which extends the ExtendableEvent interface.

Each event using ForeignFetchEvent interface has an associated potential response#foreignfetchevent-potential-responseReferenced in:4.7.2. event.respondWith(r)Handle Foreign Fetch (2) (3) (4) (5) (a response), initially set to null, an associated origin#foreignfetchevent-originReferenced in:4.7.2. event.respondWith(r)Handle Foreign Fetch (2) (a URL), initially set to null, an associated list of exposed headers#foreignfetchevent-list-of-exposed-headersReferenced in:4.7.2. event.respondWith(r)Handle Foreign Fetch (2) (whose element type is a byte string), initially set to an empty list, and the following associated flags that are initially unset:

4.7.1. event.request

request#dom-foreignfetchevent-requestReferenced in:4.7. ForeignFetchEvent4.7.1. event.request attribute must return the value it was initialized to.

4.7.2. event.respondWith(r)

Developers can set the argument r with either a promise that resolves with a Response object or a Response object (which is automatically cast to a promise). Otherwise, a network error is returned to Fetch. Renderer-side security checks about tainting for cross-origin content are tied to the types of filtered responses defined in Fetch.

respondWith(r)#dom-foreignfetchevent-respondwithReferenced in:4.7. ForeignFetchEvent4.7.2. event.respondWith(r) method must run these steps or their equivalent:

  1. If the dispatch flag is unset, then:
    1. Throw an "InvalidStateError" exception.
    2. Abort these steps.
  2. If the respond-with entered flag is set, then:
    1. Throw an "InvalidStateError" exception.
    2. Abort these steps.
  3. Set the stop propagation flag and stop immediate propagation flag.
  4. Set the respond-with entered flag.
  5. Set the wait to respond flag.
  6. Run the following substeps in parallel:
    1. Wait until r settles.
    2. If r rejected, then:
      1. Set the respond-with error flag.
    3. If r resolved with response, then:
      1. If response is a ForeignFetchResponse, then:
        1. Set the event’s origin to response.origin.
        2. Set the event’s list of exposed headers to response.headers.
        3. If response.response is disturbed or locked, then:
          1. Set the respond-with error flag.
        4. Else:
          1. Let potentialResponse be a copy of response.response's associated response, except for its body.
          2. If response.response's body is non-null, run these substeps:
            1. Set potentialResponse’s body to response.response's body.
            2. Let dummyStream be an empty ReadableStream object.
            3. Set response.response's body to a new body whose stream is dummyStream.
            4. Let reader be the result of getting a reader from dummyStream.
            5. Read all bytes from dummyStream with reader.

            These substeps are meant to produce the observable equivalent of "piping" response’s body’s stream into potentialResponse. That is, response is left with a body with a ReadableStream object that is disturbed and locked, while the data readable from potentialResponse’s body’s stream is now equal to what used to be response’s, if response’s original body is non-null.

            These substeps will be replaced by using pipe when the algorithm for pipeTo becomes stable.

          3. Set the potential response to potentialResponse.
      2. Else:
        1. Set the respond-with error flag.

        If the respond-with error flag is set, a network error is returned to Fetch through Handle Foreign Fetch algorithm. (See the step 19.1.) Otherwise, a filtered version of response is returned to Fetch through Handle Foreign Fetch algorithm. (See the step 20.1.)

    4. Unset the wait to respond flag.

4.8. ExtendableMessageEvent

[Constructor(DOMString type, optional ExtendableMessageEventInit eventInitDict), Exposed=ServiceWorker]
interface ExtendableMessageEvent : ExtendableEvent {
  readonly attribute any data;
  readonly attribute DOMString origin;
  readonly attribute DOMString lastEventId;
  [SameObject] readonly attribute (Client or ServiceWorker or MessagePort)? source;
  readonly attribute FrozenArray<MessagePort>? ports;
};
dictionary ExtendableMessageEventInit#dictdef-extendablemessageevent-extendablemessageeventinitReferenced in:4.8. ExtendableMessageEvent : ExtendableEventInit {
  any data;
  DOMString origin;
  DOMString lastEventId;
  (Client or ServiceWorker or MessagePort)? source;
  sequence<MessagePort>? ports;
};

Service workers define the extendable message event that extends the message event defined in [HTML] to allow extending the lifetime of the event. For the message event, service workers use the ExtendableMessageEvent#extendablemessage-event-interfaceReferenced in:3.1.3. postMessage(message, transfer)4.8. ExtendableMessageEvent (2)4.9. Events interface which extends the ExtendableEvent interface.

4.8.1. event.data

The data#extendablemessage-event-data-attributeReferenced in:3.1.3. postMessage(message, transfer)4.8. ExtendableMessageEvent4.8.1. event.data attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to null. It represents the message being sent.

4.8.2. event.origin

The origin#extendablemessage-event-origin-attributeReferenced in:3.1.3. postMessage(message, transfer)4.8. ExtendableMessageEvent4.8.2. event.origin attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to the empty string. It represents the origin of the service worker client that sent the message.

4.8.3. event.lastEventId

The lastEventId#extendablemessage-event-lasteventid-attributeReferenced in:4.8. ExtendableMessageEvent4.8.3. event.lastEventId attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to the empty string.

4.8.4. event.source

The source#extendablemessage-event-source-attributeReferenced in:3.1.3. postMessage(message, transfer) (2)4.8. ExtendableMessageEvent4.8.4. event.source attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to null. It represents the Client object from which the message is sent.

4.8.5. event.ports

The ports#extendablemessage-event-ports-attributeReferenced in:3.1.3. postMessage(message, transfer)4.8. ExtendableMessageEvent4.8.5. event.ports attribute must return the value it was initialized to. When the object is created, this attribute must be initialized to null. It represents the MessagePort array being sent, if any.

4.9. Events

The following events are dispatched on ServiceWorkerGlobalScope object:

Event name Interface Dispatched when…
install#service-worker-global-scope-install-eventReferenced in:2.1. Service Worker4.1.4. Event handlers4.4. ExtendableEvent (2)4.4.1. event.waitUntil(f)Install InstallEvent [Lifecycle event] The service worker’s containing service worker registration’s installing worker changes. (See step 11.2 of the Install algorithm.)
activate#service-worker-global-scope-activate-eventReferenced in:2.1. Service Worker4.1.4. Event handlers4.4. ExtendableEvent (2)4.4.1. event.waitUntil(f)Activate ExtendableEvent [Lifecycle event] The service worker’s containing service worker registration’s active worker changes. (See step 12.2 of the Activate algorithm.)
fetch#service-worker-global-scope-fetch-eventReferenced in:2.1. Service Worker2.5. Task Sources4.1.4. Event handlers4.6. FetchEvent (2)6.5. Implementer ConcernsHandle Fetch FetchEvent [Functional event] The http fetch invokes Handle Fetch with request. As a result of performing Handle Fetch, the service worker returns a response to the http fetch. The response, represented by a Response object, can be retrieved from a Cache object or directly from network using self.fetch(input, init) method. (A custom Response object can be another option.)
foreignfetch#service-worker-global-scope-foreignfetch-eventReferenced in:4.1.4. Event handlers4.7. ForeignFetchEvent (2)Handle Foreign Fetch FetchEvent [Functional event] The http fetch invokes Handle Foreign Fetch with request. As a result of performing Handle Foreign Fetch, the service worker returns a response to the http fetch. The response, represented by a Response object, can be retrieved from a Cache object or directly from network using self.fetch(input, init) method. (A custom Response object can be another option.)
message#service-worker-global-scope-message-eventReferenced in:3.1.3. postMessage(message, transfer)4.1.4. Event handlers4.8. ExtendableMessageEvent (2) ExtendableMessageEvent When it receives a message.

5. Caches

To allow authors to fully manage their content caches for offline use, the Window and the WorkerGlobalScope provide the asynchronous caching methods that open and manipulate Cache objects. An origin can have multiple, named Cache objects, whose contents are entirely under the control of scripts. Caches are not shared across origins, and they are completely isolated from the browser’s HTTP cache.

5.1. Constructs

A fetching record#dfn-fetching-recordReferenced in:5.1. Constructs (2) (3)5.4.2. matchAll(request, options) (2)5.4.4. addAll(requests) (2)5.4.5. put(request, response) (2)5.4.7. keys(request, options)Query CacheBatch Cache Operations (2) (3) is a Record {[[key]], [[value]]} where [[key]] is a Request and [[value]] is a Response.

A fetching record has an associated incumbent record#dfn-incumbent-recordReferenced in:5.4.2. matchAll(request, options)5.4.4. addAll(requests) (2)5.4.5. put(request, response) (2) (a fetching record). It is initially set to null.

A request to response map#dfn-request-to-response-mapReferenced in:5.4. Cache (2)5.4.2. matchAll(request, options) (2)5.4.4. addAll(requests) (2) (3) (4) (5)5.4.5. put(request, response) (2) (3) (4) (5)5.4.7. keys(request, options)6.6. PrivacyQuery CacheBatch Cache Operations (2) (3) (4) (5) (6) is a List of fetching records.

A name to cache map#dfn-name-to-cache-mapReferenced in:5.1. Constructs5.5. CacheStorage (2)5.5.1. match(request, options) (2)5.5.2. has(cacheName)5.5.3. open(cacheName) (2)5.5.4. delete(cacheName)5.5.5. keys()6.6. Privacy is a List of the Record {[[key]], [[value]]} where [[key]] is a string that represents a name of the Cache object and [[value]] is a Cache object.

Each origin has an associated name to cache map.

5.2. Understanding Cache Lifetimes

The Cache instances are not part of the browser’s HTTP cache. The Cache objects are exactly what authors have to manage themselves. The Cache objects do not get updated unless authors explicitly request them to be. The Cache objects do not expire unless authors delete the entries. The Cache objects do not disappear just because the service worker script is updated. That is, caches are not updated automatically. Updates must be manually managed. This implies that authors should version their caches by name and make sure to use the caches only from the version of the service worker that can safely operate on.

5.3. self.caches

partial interface Window {
  [SecureContext, SameObject] readonly attribute CacheStorage caches;
};

partial interface WorkerGlobalScope {
  [SecureContext, SameObject] readonly attribute CacheStorage caches;
};

5.3.1. caches

caches#global-caches-attributeReferenced in:5.3. self.caches#window-caches-attributeReferenced in:5.3. self.caches (2)5.3.1. caches5.4. Cache attribute must return the CacheStorage object that is associated with the context object.

5.4. Cache

[Exposed=(Window,Worker)]
interface Cache {
  [NewObject] Promise<any> match(RequestInfo request, optional CacheQueryOptions options);
  [NewObject] Promise<sequence<Response>> matchAll(optional RequestInfo request, optional CacheQueryOptions options);
  [NewObject] Promise<void> add(RequestInfo request);
  [NewObject] Promise<void> addAll(sequence<RequestInfo> requests);
  [NewObject] Promise<void> put(RequestInfo request, Response response);
  [NewObject] Promise<boolean> delete(RequestInfo request, optional CacheQueryOptions options);
  [NewObject] Promise<sequence<Request>> keys(optional RequestInfo request, optional CacheQueryOptions options);
};
dictionary CacheQueryOptions#dictdef-cache-cachequeryoptionsReferenced in:5.4. Cache (2) (3) (4) (5)5.5. CacheStorageQuery Cache {
  boolean ignoreSearch#dom-cachequeryoptions-ignoresearchReferenced in:Query Cache = false;
  boolean ignoreMethod#dom-cachequeryoptions-ignoremethodReferenced in:Query Cache = false;
  boolean ignoreVary#dom-cachequeryoptions-ignorevaryReferenced in:Query Cache = false;
  DOMString cacheName#dom-cachequeryoptions-cachenameReferenced in:5.5.1. match(request, options) (2);
};
dictionary CacheBatchOperation#dictdef-cache-cachebatchoperationReferenced in:5.4.4. addAll(requests)5.4.5. put(request, response)5.4.6. delete(request, options)Batch Cache Operations {
  DOMString type#dom-cachebatchoperation-typeReferenced in:5.4.4. addAll(requests)5.4.5. put(request, response)5.4.6. delete(request, options)Batch Cache Operations (2) (3) (4);
  Request request#dom-cachebatchoperation-requestReferenced in:5.4.4. addAll(requests)5.4.5. put(request, response)5.4.6. delete(request, options)Batch Cache Operations (2) (3) (4) (5);
  Response response#dom-cachebatchoperation-responseReferenced in:5.4.4. addAll(requests)5.4.5. put(request, response)Batch Cache Operations (2) (3) (4) (5);
  CacheQueryOptions options#dom-cachebatchoperation-optionsReferenced in:5.4.6. delete(request, options)Batch Cache Operations (2) (3);
};

A Cache#cache-interfaceReferenced in:4.9. Events (2)5. Caches (2)5.1. Constructs (2)5.2. Understanding Cache Lifetimes (2) (3) (4) (5)5.4. Cache (2) (3) (4)5.5. CacheStorage5.5.1. match(request, options) (2)5.5.3. open(cacheName) (2)6.4. Cross-Origin Resources and CORS (2) (3) object represents a request to response map. Multiple separate objects implementing the Cache interface across documents and workers can all be associated with the same request to response map simultaneously.

Cache objects are always enumerable via self.caches in insertion order (per ECMAScript 6 Map objects).

5.4.1. match(request, options)

match(request, options)#cache-match-methodReferenced in:5.4. Cache5.4.1. match(request, options)5.5.1. match(request, options) (2) (3) (4) method must run these steps or their equivalent:

  1. Let promise be a new promise.
  2. Run these substeps in parallel:
    1. Let p be the result of running the algorithm specified in matchAll(request, options) method with request and options as the arguments.
    2. Wait until p settles.
    3. If p rejects with an exception, then:
      1. Reject promise with that exception.
    4. Else if p resolves with an array, responseArray, then:
      1. If responseArray is an empty array, then:
        1. Resolve promise with undefined.
      2. Else:
        1. Resolve promise with the first element of responseArray.
  3. Return promise.

5.4.2. matchAll(request, options)

matchAll(request, options)#cache-matchall-methodReferenced in:5.4. Cache5.4.1. match(request, options)5.4.2. matchAll(request, options) method must run these steps or their equivalent:

  1. Let r be null.
  2. If the optional argument request is not omitted, then:
    1. If request is a Request object, then:
      1. Set r to request’s request.
      2. If r’s method is neither `GET` nor `HEAD` and options.ignoreMethod is false, return a promise resolved with an empty array.
    2. Else if request is a string, then:
      1. Set r to the associated request of the result of invoking the initial value of Request as constructor with request as its argument. If this throws an exception, return a promise rejected with that exception.
    3. Set r’s url’s fragment to null.
  3. Let promise be a new promise.
  4. Run these substeps in parallel:
    1. Let responseArray be an empty array.
    2. If the optional argument request is omitted, then:
      1. For each fetching record entry of its request to response map, in key insertion order:
        1. Add a copy of entry.[[value]] to responseArray.
      2. Resolve promise with responseArray.
      3. Abort these steps.
    3. Else:
      1. Let entries be the result of running Query Cache algorithm passing a Request object associated with r and options as the arguments.
      2. For each entry of entries:
        1. Let response be null.
        2. If the incumbent record incumbentRecord of the corresponding fetching record fetchingRecord in request to response map is not null, set response to a copy of incumbentRecord.[[value]].
        3. Else, set response to a copy of entry[1].
        4. If r’s method is `HEAD` and options.ignoreMethod is false, then:
          1. Let actualResponse be response’s associated response, if response’s associated response is not a filtered response, and to response’s associated response’s internal response otherwise.
          2. Set actualResponse’s body to null.
        5. Add response to responseArray.
      3. Resolve promise with responseArray.
  5. Return promise.

5.4.3. add(request)

add(request)#cache-add-methodReferenced in:5.4. Cache5.4.3. add(request) method must run these steps or their equivalent:

  1. Let requests be an array containing only request.
  2. Set responseArrayPromise to the result of running the algorithm specified in addAll(requests) passing requests as the argument.
  3. Return the result of transforming responseArrayPromise with a fulfillment handler that returns undefined.

5.4.4. addAll(requests)

addAll(requests)#cache-addAll-methodReferenced in:5.4. Cache5.4.3. add(request)5.4.4. addAll(requests) method must run these steps or their equivalent:

  1. Let responsePromiseArray be an empty array.
  2. Let requestArray be an empty array.
  3. For each request whose type is Request in requests:
    1. Let r be request’s request.
    2. If r’s url’s scheme is not one of "http" and "https", or r’s method is not `GET`, return a promise rejected with a TypeError.
  4. For each request in requests:
    1. Let r be the associated request of the result of invoking the initial value of Request as constructor with request as its argument. If this throws an exception, return a promise rejected with that exception.
    2. If r’s url’s scheme is not one of "http" and "https", then:
      1. Terminate all the ongoing fetches initiated by requests with reason fatal.
      2. Break the loop.
    3. Set r’s url’s fragment to null.
    4. Set r’s initiator to "fetch" and destination to "subresource".
    5. Add a Request object associated with r to requestArray.
    6. Let responsePromise be a new promise.
    7. Run the following substeps in parallel:
      • Fetch r.
      • To process response for response, run these substeps:
        1. If response’s type is error, or response’s status is not an ok status, reject responsePromise with a TypeError.
        2. Else if response’s header list contains a header named `Vary`, then:
          1. Let varyHeaders be the array containing the elements corresponding to the field-values of the Vary header.
          2. Let matchAsterisk be false.
          3. For each f in varyHeaders:
            1. If f matches "*", set matchAsterisk to true and break the loop.
          4. If matchAsterisk is true, reject responsePromise with a TypeError.
          5. Else, resolve responsePromise with a new Response object associated with response and a new Headers object whose guard is "immutable".
        3. Else, resolve responsePromise with a new Response object associated with response and a new Headers object whose guard is "immutable".

        This step ensures that the promise for this fetch resolves as soon as the response’s headers become available.

      • To process response body for response, do nothing.
      • To process response end-of-file for response, do nothing.
    8. Add responsePromise to responsePromiseArray.
  5. Let p be waiting for all of responsePromiseArray.
  6. Return the result of transforming p with a fulfillment handler that, when called with argument responseArray, performs the following substeps in parallel:
    1. Let operations be an empty array.
    2. For each response in responseArray with the index index:
      1. Let o be an empty object representing a CacheBatchOperation dictionary.
      2. Set the type dictionary member of o to "put".
      3. Set the request dictionary member of o to requestArray[index].
      4. Set the response dictionary member of o to response.
      5. Add o to operations.
    3. Let resultPromise be the result of running Batch Cache Operations algorithm passing operations as the argument.
    4. Return the result of transforming resultPromise with a fulfillment handler that, when called with argument responses, performs the following substeps in parallel:
      1. Let responseBodyPromiseArray be an empty array.
      2. For each response in responses:
        1. Let responseBodyPromise be a new promise.
        2. Run the following substeps in parallel:
          1. Wait for either end-of-file to have been pushed to response’s associated response r’s body or for r to have a termination reason.
          2. If r had a termination reason, then:
            1. If the incumbent record incumbentRecord of the corresponding fetching record fetchingRecord in request to response map is not null, then:
              1. Set fetchingRecord in request to response map to the copy of incumbentRecord.
            2. Else:
              1. Delete fetchingRecord from request to response map.
            3. Reject responseBodyPromise with a TypeError.
          3. Else:
            1. Set the incumbent record of the corresponding fetching record fetchingRecord in request to response map to the copy of fetchingRecord.
            2. Let invalidRecords be the result of running Query Cache algorithm passing fetchingRecord.[[key]] as the argument.
            3. For each invalidRecord in invalidRecords:
              1. If invalidRecord is not fetchingRecord, delete it from request to response map.
            4. Resolve responseBodyPromise with response.
        3. Add responseBodyPromise to responseBodyPromiseArray.
      3. Let q be waiting for all of responseBodyPromiseArray.
      4. Return the result of transforming q with a fulfillment handler that returns undefined.

5.4.5. put(request, response)

put(request, response)#cache-put-methodReferenced in:5.4. Cache5.4.5. put(request, response) method must run these steps or their equivalent:

  1. Let r be null.
  2. If request is a Request object, then:
    1. Set r to request’s request.
    2. If r’s url’s scheme is not one of "http" and "https", or r’s method is not `GET`, return a promise rejected with a TypeError.
  3. Else if request is a string, then:
    1. Set r to the associated request of the result of invoking the initial value of Request as constructor with request as its argument. If this throws an exception, return a promise rejected with that exception.
    2. If r’s url’s scheme is not one of "http" and "https", return a promise rejected with a TypeError.
  4. Set r’s url’s fragment to null.
  5. If response’s associated response’s header list contains a header named `Vary`, then:
    1. Let varyHeaders be the array containing the elements corresponding to the field-values of the Vary header.
    2. For each f in varyHeaders:
      1. If f matches "*", return a promise rejected with a TypeError.
  6. If response is disturbed or locked, return a promise rejected with a TypeError.
  7. Let newResponse be a new Response object associated with response’s associated response and a new Headers object whose guard is response’s Headers' guard.
  8. If response’s body is non-null, run these substeps:
    1. Let dummyStream be an empty ReadableStream object.
    2. Set response’s body to a new body whose stream is dummyStream.
    3. Let reader be the result of getting a reader from dummyStream.
    4. Read all bytes from dummyStream with reader.
  9. Let operations be an empty array.
  10. Let o be an empty object representing a CacheBatchOperation dictionary.
  11. Set the type dictionary member of o to "put".
  12. Set the request dictionary member of o to a Request object associated with r.
  13. Set the response dictionary member of o to newResponse.
  14. Add o to operations.
  15. Let resultPromise be the result of running Batch Cache Operations passing operations as the argument.
  16. Return the result of transforming resultPromise with a fulfillment handler that, when called with argument responses, performs the following substeps in parallel:
    1. Wait for either end-of-file to have been pushed to responses[0]'s associated response r’s body or for r to have a termination reason.
    2. If r had a termination reason, then:
      1. If the incumbent record incumbentRecord of the corresponding fetching record fetchingRecord in request to response map is not null, then:
        1. Set fetchingRecord in request to response map to the copy of incumbentRecord.
      2. Else:
        1. Delete fetchingRecord from request to response map.
      3. Throw a TypeError.
    3. Else:
      1. Set the incumbent record of the corresponding fetching record fetchingRecord in request to response map to the copy of fetchingRecord.
      2. Let invalidRecords be the result of running Query Cache algorithm passing fetchingRecord.[[key]] as the argument.
      3. For each invalidRecord in invalidRecords:
        1. If invalidRecord is not fetchingRecord, delete it from request to response map.
      4. Return undefined.

5.4.6. delete(request, options)

delete(request, options)#cache-delete-methodReferenced in:5.4. Cache5.4.6. delete(request, options) method must run these steps or their equivalent:

  1. Let r be null.
  2. If request is a Request object, then:
    1. Set r to request’s request.
    2. If r’s method is neither `GET` nor `HEAD` and options.ignoreMethod is false, return a promise resolved with false.
  3. Else if request is a string, then:
    1. Set r to the associated request of the result of invoking the initial value of Request as constructor with request as its argument. If this throws an exception, return a promise rejected with that exception.
  4. Set r’s url’s fragment to null.
  5. Let operations be an empty array.
  6. Let o be an empty object representing a CacheBatchOperation dictionary.
  7. Set the type dictionary member of o to "delete".
  8. Set the request dictionary member of o to a Request object associated with r.
  9. Set the options dictionary member of o to options.
  10. Add o to operations.
  11. Let resultPromise be the result of running Batch Cache Operations passing operations as the argument.
  12. Return the result of transforming resultPromise with a fulfillment handler, when called with argument responseArray, performs the following substeps in parallel:
    1. If responseArray is not null, return true.
    2. Else, return false.

5.4.7. keys(request, options)

keys(request, options)#cache-keys-methodReferenced in:5.4. Cache5.4.7. keys(request, options) method must run these steps or their equivalent:

  1. Let promise be a new promise.
  2. Run these substeps in parallel:
    1. Let resultArray be an empty array.
    2. If the optional argument request is omitted, then:
      1. For each fetching record entry of its request to response map, in key insertion order:
        1. Add entry.[[key]] to resultArray.
    3. Else:
      1. Let r be null.
      2. If request is a Request object, then:
        1. Set r to request’s request.
        2. If r’s method is neither `GET` nor `HEAD` and options.ignoreMethod is false, resolve promise with an empty array.
      3. Else if request is a string, then:
        1. Set r to the associated request of the result of invoking the initial value of Request as constructor with request as its argument. If this throws an exception, return a promise rejected with that exception.
      4. Set r’s url’s fragment to null.
      5. Let requestResponseArray be the result of running Query Cache algorithm passing a Request object that represents r and options as the arguments.
      6. For each requestResponse in requestResponseArray:
        1. Add requestResponse[0] to resultArray.
    4. Resolve promise with resultArray.
  3. Return promise.

5.5. CacheStorage

[SecureContext, Exposed=(Window,Worker)]
interface CacheStorage {
  [NewObject] Promise<any> match(RequestInfo request, optional CacheQueryOptions options);
  [NewObject] Promise<boolean> has(DOMString cacheName);
  [NewObject] Promise<Cache> open(DOMString cacheName);
  [NewObject] Promise<boolean> delete(DOMString cacheName);
  [NewObject] Promise<sequence<DOMString>> keys();
};

CacheStorage interface is designed to largely conform to ECMAScript 6 Map objects but entirely async, and with additional convenience methods. The methods, clear, forEach, entries and values, are intentionally excluded from the scope of the first version resorting to the ongoing discussion about the async iteration by TC39.

The user agent must create a CacheStorage object when a Window object or a WorkerGlobalScope object is created and associate it with that object.

A CacheStorage#cache-storage-interfaceReferenced in:5.3. self.caches (2)5.3.1. caches5.5. CacheStorage (2) (3) (4) (5) object represents a name to cache map of its associated global object’s environment settings object’s origin. Multiple separate objects implementing the CacheStorage interface across documents and workers can all be associated with the same name to cache map simultaneously.

5.5.1. match(request, options)

match(request, options)#cache-storage-match-methodReferenced in:5.5. CacheStorage5.5.1. match(request, options) method must run these steps or their equivalent:

  1. If options.cacheName is present, then:
    1. Return a new promise p and run the following substeps in parallel:
      1. For each Record {[[key]], [[value]]} entry of its name to cache map, in key insertion order:
        1. If options.cacheName matches entry.[[key]], then:
          1. Resolve p with the result of running the algorithm specified in match(request, options) method of Cache interface with request and options as the arguments (providing entry.[[value]] as thisArgument to the [[Call]] internal method of match(request, options).)
          2. Abort these steps.
      2. Reject p with a "NotFoundError" exception.
  2. Else:
    1. Let p be a promise resolved with undefined.
    2. For each Record {[[key]], [[value]]} entry of its name to cache map, in key insertion order:
      1. Set p to the result of transforming itself with a fulfillment handler that, when called with argument v, performs the following substeps in parallel:
        1. If v is not undefined, return v.
        2. Return the result of running the algorithm specified in match(request, options) method of Cache interface with request and options as the arguments (providing entry.[[value]] as thisArgument to the [[Call]] internal method of match(request, options).)
    3. Return p.

5.5.2. has(cacheName)

has(cacheName)#cache-storage-has-methodReferenced in:5.5. CacheStorage5.5.2. has(cacheName)5.5.4. delete(cacheName) method must run these steps or their equivalent:

  1. Return a promise p resolved with the result of running the following substeps:
    1. For each Record {[[key]], [[value]]} entry of its name to cache map, in key insertion order:
      1. If cacheName matches entry.[[key]], then:
        1. Return true.
    2. Return false.

5.5.3. open(cacheName)

open(cacheName)#cache-storage-open-methodReferenced in:5.5. CacheStorage5.5.3. open(cacheName) method must run these steps or their equivalent:

  1. Let p be a new promise.
  2. Run the following substeps:
    1. For each Record {[[key]], [[value]]} entry of its name to cache map, in key insertion order:
      1. If cacheName matches entry.[[key]], then:
        1. Resolve p with a new Cache object which is a copy of entry.[[value]].
        2. Abort these steps.
    2. Let cache be a new Cache object.
    3. Set a newly-created Record {[[key]]: cacheName, [[value]]: cache} to name to cache map. If this cache write operation failed due to exceeding the granted quota limit, reject p with a "QuotaExceededError" exception and abort these steps.
    4. Resolve p with cache.
  3. Return p.

5.5.4. delete(cacheName)

delete(cacheName)#cache-storage-delete-methodReferenced in:5.5. CacheStorage5.5.4. delete(cacheName) method must run these steps or their equivalent:

  1. Let p be the result of running the algorithm specified in has(cacheName) method with cacheName as the argument.
  2. Return the result of transforming p with a fulfillment handler that, when called with argument cacheExists, performs the following substeps in parallel:
    1. If cacheExists is true, then:
      1. Delete a Record {[[key]], [[value]]} entry from its name to cache map where cacheName matches entry.[[key]].
      2. Return true.
      3. Abort these steps.

      After this step, the existing DOM objects (i.e. the currently referenced Cache, Request, and Response objects) should remain functional.

    2. Else:
      1. Return false.

5.5.5. keys()

keys()#cache-storage-keys-methodReferenced in:5.5. CacheStorage5.5.5. keys() method must run these steps or their equivalent:

The promise returned from this method resolves with the sequence of keys, cache names in DOMString, in insertion order.

  1. Let resultArray be an empty array.
  2. Return a promise p resolved with the result of running the following substeps:
    1. For each Record {[[key]], [[value]]} entry of its name to cache map, in key insertion order:
      1. Add entry.[[key]] to resultArray.
    2. Return resultArray.

6. Security Considerations

6.1. Secure Context

Service workers must execute in secure contexts. Service worker clients must also be secure contexts to register a service worker registration, to get access to the service worker registrations and the service workers, to do messaging with the service workers, and to be manipulated by the service workers. This effectively means that service workers and their service worker clients should be hosted over HTTPS. A user agent may allow localhost, 127.0.0.0/8, and ::1/128 for development purpose. (Note that they may still be secure contexts.) The primary reason for this restriction is to protect users from the risks associated with insecure contexts.

6.2. Content Security Policy

Whenever a user agent invokes Run Service Worker algorithm with a service worker serviceWorker:

  • If serviceWorker’s script resource was delivered with a Content-Security-Policy HTTP header containing the value policy, the user agent must enforce policy for serviceWorker.
  • If serviceWorker’s script resource was delivered with a Content-Security-Policy-Report-Only HTTP header containing the value policy, the user agent must monitor policy for serviceWorker.

The primary reason for this restriction is to mitigate a broad class of content injection vulnerabilities, such as cross-site scripting (XSS).

6.3. Origin Relativity

6.3.1. Origin restriction

This section is non-normative.

A Service worker executes in the registering service worker client’s origin. One of the advanced concerns that major applications would encounter is whether they can be hosted from a CDN. By definition, these are servers in other places, often on other origins. Therefore, service workers cannot be hosted on CDNs. But they can include resources via importScripts(). The reason for this restriction is that service workers create the opportunity for a bad actor to turn a bad day into a bad eternity.

6.3.2. importScripts(urls)

When the importScripts(urls)#importscripts-methodReferenced in:6.3.1. Origin restriction method is called on a ServiceWorkerGlobalScope object, the user agent must import scripts into worker global scope, with the following options:

To validate the state, the user agent must do nothing.

To get a fetch result, the user agent must run the following steps:

  1. Let serviceWorker be the settings object’s global object’s service worker.
  2. If serviceWorker’s imported scripts updated flag is unset, then:
    1. Attempt to fetch each resource identified by the resulting absolute URLs, from the origin specified by settings object, using the referrer source specified by settings object, and with the blocking flag set.
  3. Else:
    1. If there exists a corresponding Record record for url in serviceWorker’s script resource map, set the script resource to record.[[value]].
    2. Else, set the script resource to null.

To postprocess the fetch result, the user agent must run the following steps:

  1. If serviceWorker’s imported scripts updated flag is unset, then:
    1. If the fetching attempt failed (e.g. the server returned a 4xx or 5xx status code or equivalent, or there was a DNS error), throw a "NetworkError" exception and abort all these steps.
    2. Else:
      1. If there exists a corresponding Record record for the resulting absolute URL url in serviceWorker’s script resource map, set record.[[value]] to the fetched script resource.
      2. Else, set a newly-created Record {[[key]]: url, [[value]]: the fetched script resource} to serviceWorker’s script resource map.
  2. Else, if the script resource is null, throw a "NetworkError" exception and abort all these steps.

6.4. Cross-Origin Resources and CORS

This section is non-normative.

Applications tend to cache items that come from a CDN or other origin. It is possible to request many of them directly using <script>, <img>, <video> and <link> elements. It would be hugely limiting if this sort of runtime collaboration broke when offline. Similarly, it is possible to fetch many sorts of off-origin resources when appropriate CORS headers are set.

Service workers enable this by allowing Caches to fetch and cache off-origin items. Some restrictions apply, however. First, unlike same-origin resources which are managed in the Cache as Response objects whose corresponding responses are basic filtered response, the objects stored are Response objects whose corresponding responses are either CORS filtered responses or opaque filtered responses. They can be passed to event.respondWith(r) method in the same manner as the Response objects whose corresponding responses are basic filtered responses, but cannot be meaningfully created programmatically. These limitations are necessary to preserve the security invariants of the platform. Allowing Caches to store them allows applications to avoid re-architecting in most cases.

6.5. Implementer Concerns

This section is non-normative.

The implementers are encouraged to note:

6.6. Privacy

Service workers introduce new persistent storage features including scope to registration map (for service worker registrations and their service workers), request to response map and name to cache map (for caches), and script resource map (for script resources). In order to protect users from any potential unsanctioned tracking threat, these persistent storages should be cleared when users intend to clear them and should maintain and interoperate with existing user controls e.g. purging all existing persistent storages.

7. Storage Considerations

Service workers should take a dependency on Quota Management API that extends the ServiceWorkerGlobalScope with the event listeners onbeforeevicted and onevicted to detect a storage pressure and give pre-eviction information to the application.

The cache write operations in service workers when failed due to exceeding the granted quota limit should throw "QuotaExceededError" exception.

8. Extensibility

Service workers are extensible from other specifications.

8.1. Define API bound to Service Worker Registration

Specifications may define an API tied to a service worker registration by using partial interface definition to the ServiceWorkerRegistration interface where it may define the specification specific attributes and methods:

partial interface ServiceWorkerRegistration {
  // e.g. define an API namespace
  readonly attribute APISpaceType APISpace;
  // e.g. define a method
  Promise<T> methodName(list of arguments);
};

8.2. Define Functional Event

Specifications may define a functional event by extending ExtendableEvent interface:

// e.g. define FunctionalEvent interface
interface FunctionalEvent : ExtendableEvent {
  // add a functional event’s own attributes and methods
};

8.3. Define Event Handler

Specifications may define an event handler attribute for the corresponding functional event using partial interface definition to the ServiceWorkerGlobalScope interface:

partial interface ServiceWorkerGlobalScope {
  attribute EventHandler onfunctionalevent;
};

8.4. Request Functional Event Dispatch

To request a functional event dispatch to a service worker, specifications may invoke Handle Functional Event algorithm, or its equivalent, with its service worker registration registration and the algorithm callbackSteps as the arguments.

Specifications may define an algorithm callbackSteps where the corresponding functional event can be created and fired with specification specific objects. The algorithm is passed globalObject (a ServiceWorkerGlobalScope object) at which it may fire its functional events. This algorithm is called on a task queued by Handle Functional Event algorithm.

See an example hook defined in Notifications API.

Appendix A: Algorithms

The following definitions are the user agent’s internal data structures used throughout the specification.

A scope to registration map#dfn-scope-to-registration-mapReferenced in:2.2.1. Lifetime2.4. Selection and Use (2)3.4.2. ready3.4.5. getRegistrations()6.6. PrivacyHandle Functional EventHandle User Agent ShutdownSet RegistrationClear RegistrationMatch Service Worker RegistrationGet Registration is a List of the Record {[[key]], [[value]]} where [[key]] is a string that represents a scope url and [[value]] is a service worker registration.

A job#dfn-jobReferenced in:Appendix A: Algorithms (2) (3) (4) (5) (6) (7) (8) (9) (10) (11) (12) (13) (14)Create Job (2)Schedule JobFinish JobResolve Job PromiseReject Job PromiseRegisterUpdateInstallUnregister is an abstraction of one of register, update, and unregister request for a service worker registration.

A job has a job type#dfn-job-typeReferenced in:Appendix A: AlgorithmsCreate Job (2)Run Job (2) (3)Update, which is one of register, update, and unregister.

A job has a scope url#dfn-job-scope-urlReferenced in:Appendix A: Algorithms (2) (3)Create JobRegister (2) (3)UpdateUnregister (2) (a URL).

A job has a script url#dfn-job-script-urlReferenced in:Appendix A: AlgorithmsCreate JobRegister (2) (3)Update (2) (3) (4) (5) (6) (7) (a URL).

A job has a worker type#dfn-job-worker-typeReferenced in:3.2.5. update()3.4.3. register(scriptURL, options)Update (2)Soft Update ("classic" or "module").

A job has a client#dfn-job-clientReferenced in:Create JobRegister (2)Update (2)Unregister (a service worker client). It is initially null.

A job has a promise#dfn-job-promiseReferenced in:Create JobSchedule Job (2)Resolve Job PromiseReject Job PromiseInstall (a promise). It is initially null.

A job has a list of equivalent job promises#dfn-job-list-of-equivalent-job-promisesReferenced in:Schedule JobResolve Job PromiseReject Job Promise (a list of promises). It is initially the empty list.

A job has a force bypass cache flag#dfn-job-force-bypass-cache-flagReferenced in:Soft Update It is initially unset.

Two jobs are equivalent#dfn-job-equivalentReferenced in:Schedule Job when their job type is the same and:

A job queue#dfn-job-queueReferenced in:Appendix A: Algorithms (2) (3) (4) (5) (6)Schedule Job (2) (3) (4)Run Job (2)Finish Job (2) (3) (4) is a thread safe queue used to synchronize the set of concurrent jobs. The job queue contains jobs as its elements. The job queue should satisfy the general properties of FIFO queue. A user agent must maintain a separate job queue for each service worker registration keyed by its scope url. A job queue is initially empty. Unless stated otherwise, the job queue referenced from the algorithm steps is a job queue for the job’s scope url.

Create Job

Input
jobType, a job type
scopeURL, a URL
scriptURL, a URL
promise, a promise
client, a service worker client
Output
job, a job
  1. Let job be a new job.
  2. Set job’s job type to jobType.
  3. Set job’s scope url to scopeURL.
  4. Set job’s script url to scriptURL.
  5. Set job’s promise to promise.
  6. Set job’s client to client.
  7. Return job.

Schedule Job

Input
job, a job
Output
none
  1. If the job queue is empty, then:
    1. Push job to the job queue and invoke Run Job.
  2. Else:
    1. Let lastJob be the element at the back of the job queue.
    2. If job is equivalent to lastJob and lastJob’s promise has not settled, append job’s promise to lastJob’s list of equivalent job promises.
    3. Else, push job to the job queue.

Run Job

Input
none
Output
none
  1. Assert: the job queue is not empty.
  2. Queue a task to run these steps:
    1. Let job be the element in the front of the job queue.
    2. If job’s job type is register, run Register with job in parallel.
    3. Else if job’s job type is update, run Update with job in parallel.

      For a register job and an update job, the user agent delays queuing a task for running the job until after the document initiated the job has been dispatched DOMContentLoaded event.

    4. Else if job’s job type is unregister, run Unregister with job in parallel.

Finish Job

Input
job, a job
Output
none
  1. Assert: the top element in the job queue is job.
  2. Pop the top element from the job queue.
  3. If the job queue is not empty, invoke Run Job with the top element of the job queue.

Resolve Job Promise

Input
job, a job
value, any
Output
none
  1. Resolve job’s promise with value.
  2. For each promise in job’s list of equivalent job promises:
    1. Resolve promise with value.

Reject Job Promise

Input
job, a job
reason, an exception
Output
none
  1. Reject job’s promise with reason.
  2. For each promise in job’s list of equivalent job promises:
    1. Reject promise with reason.

Register

Input
job, a job
Output
promise, a promise
  1. If the result of running Is origin potentially trustworthy with the origin of job’s script url as the argument is Not Trusted, then:
    1. Invoke Reject Job Promise with job and a "SecurityError" exception.
    2. Invoke Finish Job with job and abort these steps.
  2. If the origin of job’s script url is not job’s client’s origin, then:
    1. Invoke Reject Job Promise with job and a "SecurityError" exception.
    2. Invoke Finish Job with job and abort these steps.
  3. If the origin of job’s scope url is not job’s client’s origin, then:
    1. Invoke Reject Job Promise with job and a "SecurityError" exception.
    2. Invoke Finish Job with job and abort these steps.
  4. Let registration be the result of running the Get Registration algorithm passing job’s scope url as the argument.
  5. If registration is not null, then:
    1. If registration’s uninstalling flag is set, unset it.
    2. Let newestWorker be the result of running the Get Newest Worker algorithm passing registration as the argument.
    3. If newestWorker is not null and job’s script url equals newestWorker’s script url, then:
      1. If newestWorker is an active worker, then:
        1. Invoke Resolve Job Promise with job and the ServiceWorkerRegistration object which represents registration.
        2. Invoke Finish Job with job and abort these steps.
  6. Else:
    1. Invoke Set Registration algorithm passing job’s scope url as its argument.
  7. Invoke Update algorithm, or its equivalent, passing job as the argument.

Update

Input
job, a job
Output
none
  1. Let registration be the result of running the Get Registration algorithm passing job’s scope url as the argument.
  2. If registration is null or registration’s uninstalling flag is set, then:
    1. Invoke Reject Job Promise with job and a TypeError.
    2. Invoke Finish Job with job and abort these steps.
  3. Let newestWorker be the result of running Get Newest Worker algorithm passing registration as the argument.
  4. If job’s job type is update, and newestWorker’s script url is not job’s script url, then:
    1. Invoke Reject Job Promise with job and a TypeError.
    2. Invoke Finish Job with job and abort these steps.
  5. Switching on job’s worker type, run these substeps with the following options:
    "classic"

    Fetch a classic worker script given job’s serialized script url, job’s client, and "serviceworker".

    "module"

    Fetch a module script tree given job’s serialized script url, "omit", "serviceworker", and job’s client.

    To set up the request given request, run the following steps:

    1. Append `Service-Worker`/`script` to request’s header list.

      See the definition of the Service-Worker header in Appendix B: Extended HTTP headers.

    2. Set request’s skip service worker flag and request’s redirect mode to "error".
    3. If newestWorker is not null and registration’s last update check time is not null, then:
      1. If the time difference in seconds calculated by the current time minus registration’s last update check time is greater than 86400, or force bypass cache flag is set, set request’s cache mode to "reload".

      Even if the cache mode is not set to "reload", the user agent obeys Cache-Control header’s max-age value in the network layer to determine if it should bypass the browser cache.

    To validate the response given response, run the following steps:

    1. Extract a MIME type from the response’s header list. If this MIME type (ignoring parameters) is not one of text/javascript, application/x-javascript, and application/javascript, then:
      1. Invoke Reject Job Promise with job and a "SecurityError" exception.
      2. If newestWorker is null, invoke Clear Registration algorithm passing registration as its argument.
      3. Invoke Finish Job with job.
      4. Return false and abort these steps.
    2. Let serviceWorkerAllowed be the result of parsing `Service-Worker-Allowed` in response’s header list.

      See the definition of the Service-Worker-Allowed header in Appendix B: Extended HTTP headers.

    3. If serviceWorkerAllowed is failure, then:
      1. Invoke Reject Job Promise with job and a TypeError.
      2. If newestWorker is null, invoke Clear Registration algorithm passing registration as its argument.
      3. Invoke Finish Job with job.
      4. Return false and abort these steps.
    4. Let scopeURL be registration’s scope url.
    5. Let maxScopeString be null.
    6. If serviceWorkerAllowed is null, then:
      1. Set maxScopeString to "/" concatenated with the strings, except the last string that denotes the script’s file name, in job’s script url’s path (including empty strings), separated from each other by "/".
    7. Else:
      1. Let maxScope be the result of parsing serviceWorkerAllowed with job’s script url.
      2. Set maxScopeString to "/" concatenated with the strings in maxScope’s path (including empty strings), separated from each other by "/".
    8. Let scopeString be "/" concatenated with the strings in scopeURL’s path (including empty strings), separated from each other by "/".
    9. If scopeString starts with maxScopeString, do nothing.
    10. Else:
      1. Invoke Reject Job Promise with job and a "SecurityError" exception.
      2. If newestWorker is null, invoke Clear Registration algorithm passing registration as its argument.
      3. Invoke Finish Job with job.
      4. Return false and abort these steps.
    11. If response’s cache state is not "local", set registration’s last update check time to the current time.
    12. Return true.

    If the algorithm asynchronously completes with null, then:

    1. Invoke Reject Job Promise with job and a TypeError.
    2. If newestWorker is null, invoke Clear Registration algorithm passing registration as its argument.
    3. Invoke Finish Job with job and abort these steps.

    Else, continue the rest of these steps after the algorithm’s asynchronous completion, with script being the asynchronous completion value.

  6. If newestWorker is not null, newestWorker’s script url equals job’s script url with the exclude fragments flag set, and script is a byte-for-byte match with newestWorker’s script resource, then:
    1. Invoke Resolve Job Promise with job and the ServiceWorkerRegistration object which represents registration.
    2. Invoke Finish Job with job and abort these steps.
  7. Else:
    1. Let worker be a new service worker.
    2. Generate a unique opaque string and set worker’s id to the value.
    3. Set worker’s script url to job’s script url, worker’s script resource to script, and worker’s type to job’s worker type.
    4. Invoke Run Service Worker algorithm with worker as the argument.
    5. If an uncaught runtime script error occurs during the above step, then:
      1. Invoke Reject Job Promise with job and a TypeError.
      2. If newestWorker is null, invoke Clear Registration algorithm passing registration as its argument.
      3. Invoke Finish Job with job and abort these steps.
  8. Invoke Install algorithm, or its equivalent, with job, worker, and registration as its arguments.

Soft Update

The user agent may call this as often as it likes to check for updates.

Input
registration, a service worker registration
force bypass cache flag, an optional flag unset by default

Implementers may use the force bypass cache flag to aid debugging (e.g. invocations from developer tools), and other specifications that extend service workers may also use the flag on their own needs.

Output
None
  1. Let newestWorker be the result of running Get Newest Worker algorithm passing registration as its argument.
  2. If newestWorker is null, abort these steps.
  3. Let job be the result of running Create Job with update, registration’s scope url, newestWorker’s script url, a new promise, and null.
  4. Set job’s worker type to newestWorker’s type.
  5. Set job’s force bypass cache flag if its force bypass cache flag is set.
  6. Invoke Schedule Job with job.

Install

Input
job, a job
worker, a service worker
registration, a service worker registration
Output
none
  1. Let installFailed be false.
  2. Let newestWorker be the result of running Get Newest Worker algorithm passing registration as its argument.
  3. Let redundantWorker be null.
  4. Run the Update Registration State algorithm passing registration, "installing" and worker as the arguments.
  5. Run the Update Worker State algorithm passing registration’s installing worker and installing as the arguments.
  6. Assert: job’s promise is not null.
  7. Invoke Resolve Job Promise with job and the ServiceWorkerRegistration object which represents registration.
  8. Queue a task to fire a simple event named updatefound at all the ServiceWorkerRegistration objects for all the service worker clients whose creation url matches registration’s scope url and all the service workers whose containing service worker registration is registration.
  9. Let installingWorker be registration’s installing worker.
  10. Invoke Run Service Worker algorithm with installingWorker as the argument.
  11. Queue a task task to run the following substeps:
    1. Create a trusted event e that uses the InstallEvent interface, with the event type install, which does not bubble, is not cancelable, and has no default action.
    2. Dispatch e at installingWorker’s environment settings object’s global object globalObject.
    3. Let extendLifetimePromises be an empty array.
    4. For each event listener invoked:
      1. If any uncaught runtime script error occurs, then:
        1. Report the error for the script per the runtime script errors handling.
        2. Set redundantWorker to registration’s installing worker.
        3. Run the Update Registration State algorithm passing registration, "installing" and null as the arguments.
        4. Run the Update Worker State algorithm passing redundantWorker and redundant as the arguments.
        5. If newestWorker is null, invoke Clear Registration algorithm passing registration as its argument.
        6. Invoke Finish Job with job and abort these steps.
      2. Let eventObject be the first argument passed to this event listener.
      3. Append eventObject’s extend lifetime promises to extendLifetimePromises.
    5. Let p be waiting for all of extendLifetimePromises.
    6. Run the following substeps in parallel:
      1. Wait until p settles.
      2. If p rejected, set installFailed to true.
      3. Else if p resolved with a value, do nothing.

    If task is discarded or the script has been aborted by the termination of installingWorker, set installFailed to true.

  12. Wait for task to have executed or been discarded.
  13. If installFailed is true, then:
    1. Set redundantWorker to registration’s installing worker.
    2. Run the Update Registration State algorithm passing registration, "installing" and null as the arguments.
    3. Run the Update Worker State algorithm passing redundantWorker and redundant as the arguments.
    4. If newestWorker is null, invoke Clear Registration algorithm passing registration as its argument.
    5. Invoke Finish Job with job and abort these steps.
  14. Set registration’s installing worker’s imported scripts updated flag.
  15. If registration’s waiting worker is not null, then:
    1. Set redundantWorker to registration’s waiting worker.
    2. Terminate redundantWorker.
    3. The user agent may abort in-flight requests triggered by redundantWorker.
  16. Run the Update Registration State algorithm passing registration, "waiting" and registration’s installing worker as the arguments.
  17. Run the Update Registration State algorithm passing registration, "installing" and null as the arguments.
  18. Run the Update Worker State algorithm passing registration’s waiting worker and installed as the arguments.
  19. If redundantWorker is not null, run the Update Worker State algorithm passing redundantWorker and redundant as the arguments.
  20. If registration’s waiting worker’s skip waiting flag is set, then:
    1. Run Activate algorithm, or its equivalent, passing registration as the argument.
    2. Invoke Finish Job with job and abort these steps.
  21. Invoke Finish Job with job.
  22. Wait for all the tasks queued by Update Worker State invoked in this algorithm have executed.
  23. Wait until no service worker client is using registration or registration’s waiting worker’s skip waiting flag is set.
  24. If registration’s waiting worker waitingWorker is not null and waitingWorker’s skip waiting flag is not set, invoke Activate algorithm, or its equivalent, with registration as its argument.

Activate

Input
registration, a service worker registration
Output
None
  1. If registration’s waiting worker is null, abort these steps.
  2. Let redundantWorker be null.
  3. If registration’s active worker is not null, then:
    1. Set redundantWorker to registration’s active worker.
    2. Wait for redundantWorker to finish handling any in-progress requests.
    3. Terminate redundantWorker.
  4. Run the Update Registration State algorithm passing registration, "active" and registration’s waiting worker as the arguments.
  5. Run the Update Registration State algorithm passing registration, "waiting" and null as the arguments.
  6. Run the Update Worker State algorithm passing registration’s active worker and activating as the arguments.

    Once an active worker is activating, neither a runtime script error nor a force termination of the active worker prevents the active worker from getting activated.

  7. If redundantWorker is not null, run the Update Worker State algorithm passing redundantWorker and redundant as the arguments.
  8. For each service worker client client whose creation url matches registration’s scope url:
    1. If client is a window client, unassociate client’s responsible document from its application cache, if it has one.
    2. Else if client is a shared worker client, unassociate client’s global object from its application cache, if it has one.

    Resources will now use the service worker registration instead of the existing application cache.

  9. For each service worker client client who is using registration:
    1. Set client’s active worker to registration’s active worker.
    2. Invoke Notify Controller Change algorithm with client as the argument.
  10. Let activeWorker be registration’s active worker.
  11. Invoke Run Service Worker algorithm with activeWorker as the argument.
  12. Queue a task task to run the following substeps:
    1. Create a trusted event e that uses the ExtendableEvent interface, with the event type activate, which does not bubble, is not cancelable, and has no default action.
    2. Dispatch e at activeWorker’s environment settings object’s global object.
    3. Let extendLifetimePromises be an empty array.
    4. For each event listener invoked:
      1. If any uncaught runtime script error occurs, report the error for the script per the runtime script errors handling.
      2. Let eventObject be the first argument passed to this event listener.
      3. Append eventObject’s extend lifetime promises to extendLifetimePromises.
    5. Let p be waiting for all of extendLifetimePromises.
  13. Wait for task to have executed and p defined in task has settled, or task to have been discarded or the script to have been aborted by the termination of activeWorker.
  14. Run the Update Worker State algorithm passing registration’s active worker and activated as the arguments.

Run Service Worker

Input
serviceWorker, a service worker
Output
None
  1. Let script be serviceWorker’s script resource.
  2. Assert: script is not null.
  3. If serviceWorker is already running, abort these steps.
  4. Create a separate parallel execution environment (i.e. a separate thread or process or equivalent construct), and run the rest of these steps in that context.
  5. Call the JavaScript InitializeHostDefinedRealm() abstract operation with the following customizations:
  6. Let workerEventLoop be a newly created event loop.
  7. Let workerGlobalScope be realmExecutionContext’s global object.
  8. Let settingsObject be a new environment settings object whose algorithms are defined as follows:
    The realm execution context
    Return realmExecutionContext.
    The global object
    Return workerGlobalScope.
    The responsible event loop
    Return workerEventLoop.
    The referrer source
    Return serviceWorker’s script url.

    Remove this definition after sorting out the referencing sites.

    The API URL character encoding
    Return UTF-8.
    The API base URL
    Return serviceWorker’s script url.
    The origin and effective script origin
    Return its registering service worker client’s origin.
    The creation URL
    Return workerGlobalScope’s url.
    The HTTPS state
    Return workerGlobalScope’s HTTPS state.
  9. Set workerGlobalScope’s url to serviceWorker’s script url.
  10. Set workerGlobalScope’s HTTPS state to serviceWorker’s script resource’s HTTPS state.
  11. Set workerGlobalScope’s type to serviceWorker’s type.
  12. Create a new WorkerLocation object and associate it with workerGlobalScope.
  13. If serviceWorker is an active worker, and there are any tasks queued in serviceWorker’s containing service worker registration’s task queues, queue them to serviceWorker’s event loop’s task queues in the same order using their original task sources.
  14. If script is a classic script, then run the classic script script. Otherwise, it is a module script; run the module script script.

    In addition to the usual possibilities of returning a value or failing due to an exception, this could be prematurely aborted by the kill a worker or terminate a worker algorithms.

  15. If script’s has ever been evaluated flag is unset, then:
    1. Set workerGlobalScope’s associated service worker’s set of event types to handle to the set of event types created from settingsObject’s global object’s associated list of event listeners' event types.

      If the global object’s associated list of event listeners does not have any event listener added at this moment, the service worker’s set of event types to handle is set to an empty set. The user agents are encouraged to show a warning that the event listeners must be added on the very first evaluation of the worker script.

    2. Set script’s has ever been evaluated flag.
  16. Run the responsible event loop specified by settingsObject until it is destroyed.
  17. Empty workerGlobalScope’s list of active timers.

Terminate Service Worker

Input
serviceWorker, a service worker
Output
None
  1. If serviceWorker is not running, abort these steps.
  2. Let serviceWorkerGlobalScope be serviceWorker’s environment settings object’s global object.
  3. Set serviceWorkerGlobalScope’s closing flag to true.
  4. If there are any tasks, whose task source is either the handle fetch task source or the handle functional event task source, queued in serviceWorkerGlobalScope’s event loop’s task queues, queue them to serviceWorker’s containing service worker registration’s corresponding task queues in the same order using their original task sources, and discard all the tasks (including tasks whose task source is neither the handle fetch task source nor the handle functional event task source) from serviceWorkerGlobalScope’s event loop’s task queues without processing them.

    This effectively means that the fetch events and the other functional events such as push events are backed up by the registration’s task queues while the other tasks including message events are discarded.

  5. Abort the script currently running in serviceWorker.

Handle Fetch

The Handle Fetch algorithm is the entry point for the fetch handling handed to the service worker context.

Input
request, a request
Output
response, a response
  1. Let handleFetchFailed be false.
  2. Let respondWithEntered be false.
  3. Let eventCanceled be false.
  4. Let r be a new Request object associated with request.
  5. Let headersObject be r’s headers attribute value.
  6. Set headersObject’s guard to immutable.
  7. Let response be null.
  8. Let registration be null.
  9. Let client be the service worker client that corresponds to request’s client.
  10. Assert: request’s destination is not "serviceworker".
  11. If request is a potential-navigation-or-subresource request, then:
    1. Return null.
  12. Else if request is a non-subresource request, then:

    If the non-subresource request is under the scope of a service worker registration, application cache is completely bypassed regardless of whether the non-subresource request uses the service worker registration.

    1. If client is not a secure context, return null.
    2. If request is a navigation request and the navigation triggering it was initiated with a shift+reload or equivalent, return null.
    3. Set registration to the result of running Match Service Worker Registration algorithm, or its equivalent, passing request’s url as the argument.
    4. If registration is null or registration’s active worker is null, return null.
    5. Set client’s active worker to registration’s active worker.

    From this point, the service worker client starts to use its active worker’s containing service worker registration.

  13. Else if request is a subresource request, then:
    1. If client’s active worker is non-null, set registration to client’s active worker’s containing service worker registration.
    2. Else, return null.
  14. Let activeWorker be registration’s active worker.
  15. If activeWorker’s set of event types to handle does not contain fetch, return null.

    To avoid unnecessary delays, the Handle Fetch enforces early return when no event listeners have been deterministically added in the service worker’s global during the very first script execution.

  16. If activeWorker’s state is activating, wait for activeWorker’s state to become activated.
  17. Invoke Run Service Worker algorithm with activeWorker as the argument.
  18. Queue a task task to run the following substeps:
    1. Create a trusted event e that uses the FetchEvent interface, with the event type fetch, which does not bubble and has no default action.
    2. Let the request attribute of e be initialized to r.
    3. Let the clientId attribute of e be initialized to client’s id if request is not a non-subresource request, and to null otherwise.
    4. Let the isReload attribute of e be initialized to true if request’s client is a window client and the event was dispatched with the user’s intention for the page reload, and false otherwise.
    5. Dispatch e at activeWorker’s environment settings object’s global object.
    6. For each event listener invoked:
      1. If any uncaught runtime script error occurs, then:
        1. Report the error for the script per the runtime script errors handling.
        2. Abort these steps.
      2. Let event be the event for which this event listener was invoked.
      3. If event’s respond-with entered flag is set, set respondWithEntered to true.
      4. If event’s wait to respond flag is set, then:
        1. Wait until event’s wait to respond flag is unset.
        2. If event’s respond-with error flag is set, set handleFetchFailed to true.
        3. Else, set response to event’s potential response.
      5. If event’s canceled flag is set, set eventCanceled to true.

    If task is discarded or the script has been aborted by the termination of activeWorker, set handleFetchFailed to true.

    The task must use activeWorker’s event loop and the handle fetch task source.

  19. Wait for task to have executed or been discarded.
  20. If respondWithEntered is false, then:
    1. If eventCanceled is true, return a network error and continue running these substeps in parallel.
    2. Else, return null and continue running these substeps in parallel.
    3. If request is a non-subresource request, or request is a subresource request and the time difference in seconds calculated by the current time minus registration’s last update check time is greater than 86400, invoke Soft Update algorithm, or its equivalent, with registration.
    4. Abort these steps.
  21. If handleFetchFailed is true, then:
    1. Return a network error and continue running these substeps in parallel.
    2. If request is a non-subresource request, or request is a subresource request and the time difference in seconds calculated by the current time minus registration’s last update check time is greater than 86400, invoke Soft Update algorithm, or its equivalent, with registration.
  22. Else:
    1. Return response and continue running these substeps in parallel.
    2. If request is a non-subresource request, or request is a subresource request and the time difference in seconds calculated by the current time minus registration’s last update check time is greater than 86400, invoke Soft Update algorithm, or its equivalent, with registration.

Handle Foreign Fetch

The Handle Foreign Fetch algorithm is the entry point for the fetch handling handed to the service worker context to handle foreign fetch requests.

This needs an extra step in the HTTP fetch algorithm in between step 3 and 4, to call this algorithm for all requests if response is null at that point.

Input
request, a request
Output
response, a response
  1. Let handleFetchFailed be false.
  2. Let respondWithEntered be false.
  3. Let eventCanceled be false.
  4. If request is not a subresource request, return null and abort these steps.

    Foreign fetch only allows intercepting of subresource requests. Navigation requests can be intercepted by the regular fetch event anyway, so there is no benefit to supporting those requests here as well.

  5. If request’s client is not a secure context, return null and abort these steps.
  6. Let activeWorker be the result of running the Match Service Worker for Foreign Fetch algorithm passing request’s url as the argument.
  7. If activeWorker is null, return null.
  8. If activeWorker’s state is activating, then:
    1. Wait for activeWorker’s state to become activated.
  9. If activeWorker’s origin is the same as request’s origin, return null.
  10. Let originMatches be false.
  11. If activeWorker’s list of foreign fetch origins is empty, set originMatches to true.
  12. For each origin in activeWorker’s list of foreign fetch origins:
    1. If origin is equal to request’s origin, set originMatches to true.
  13. If originMatches is false, return null.
  14. Let r be a new Request object associated with request.
  15. Invoke Run Service Worker algorithm with activeWorker as the argument.
  16. Queue a task task to run the following substeps:
    1. Create a trusted event e that uses the ForeignFetchEvent interface, with the event type foreignfetch, which does not bubble and has no default action.
    2. Let the request attribute of e be initialized to r.
    3. Dispatch e at activeWorker’s environment settings object’s global object.
    4. For each event listener invoked:
      1. If any uncaught runtime script error occurs, then:
        1. Report the error for the script per the runtime script errors handling.
        2. Abort these steps.
      2. Let event be the event for which this event listener was invoked.
      3. If event’s respond-with entered flag is set, then:
        1. Set respondWithEntered to true.
      4. If event’s wait to respond flag is set, then:
        1. Wait until event’s wait to respond flag is unset.
      5. Let internalResponse be event’s potential response.
      6. If internalResponse is a filtered response, set internalResponse to internalResponse’s internal response.
      7. If event’s respond-with error flag is set, set handleFetchFailed to true.
      8. Else if event’s origin is null:
        1. If event’s list of exposed headers is not empty, set handleFetchFailed to true.
        2. Else if event’s potential response is a opaque-redirect filtered response, set response to event’s potential response.
        3. Else set response to an opaque filtered response of internalResponse.
      9. Else if event’s origin is not equal to request’s origin, set handleFetchFailed to true.
      10. Else if event’s potential response is an opaque filtered response or is an opaque-redirect filtered response, set response to event’s potential response.
      11. Else if request’s response tainting is "opaque", set response to an opaque filtered response of internalResponse.
      12. Else:
        1. Let headers be event’s list of exposed headers.
        2. If response is a CORS filtered response, remove from internalResponse’s CORS-exposed header-names list all values not in headers.
        3. Else set internalResponse’s CORS-exposed header-names list to headers.
        4. Set response to a CORS filtered response of internalResponse.
      13. If event’s canceled flag is set, then:
        1. Set eventCanceled to true.

    If task is discarded or the script has been aborted by the termination of activeWorker, set handleFetchFailed to true.

    The task must use activeWorker’s event loop and the handle fetch task source.

  17. Wait for task to have executed or been discarded.
  18. If respondWithEntered is false, then:
    1. If eventCanceled is true, then:
      1. Return a network error.
    2. Else:
      1. Return null.
  19. If handleFetchFailed is true, then:
    1. Return a network error.
  20. Else:
    1. Return response.

Handle Functional Event

Input
registration, a service worker registration
callbackSteps, an algorithm
Output
None
  1. Assert: a Record with the [[value]] equals to registration is contained in scope to registration map.
  2. Assert: registration’s active worker is not null.
  3. Let activeWorker be registration’s active worker.
  4. If activeWorker’s set of event types to handle does not contain the event type for this functional event, return.

    To avoid unnecessary delays, the Handle Functional Event enforces early return when no event listeners have been deterministically added in the service worker’s global during the very first script execution.

  5. If activeWorker’s state is activating, wait for activeWorker’s state to become activated.
  6. Invoke Run Service Worker algorithm with activeWorker as the argument.
  7. Queue a task task to invoke callbackSteps with activeWorker’s environment settings object’s global object as its argument.

    The task must use activeWorker’s event loop and the handle functional event task source.

  8. Wait for task to have executed or been discarded.
  9. If the time difference in seconds calculated by the current time minus registration’s last update check time is greater than 86400, invoke Soft Update algorithm, or its equivalent, with registration.

Handle Service Worker Client Unload

The user agent must run these steps, or their equivalent, when a service worker client unloads by unloading, being killed, or terminating.

Input
client, a service worker client
Output
None
  1. Run the following steps atomically.
  2. Let registration be the service worker registration used by client.
  3. If registration is null, abort these steps.
  4. If any other service worker client is using registration, abort these steps.
  5. If registration’s uninstalling flag is set, invoke Clear Registration algorithm passing registration as its argument and abort these steps.
  6. If registration’s waiting worker is not null, run Activate algorithm, or its equivalent, with registration as the argument.

Handle User Agent Shutdown

Input
None
Output
None
  1. For each Record {[[key]], [[value]]} entry of its scope to registration map:
    1. Let registration be entry.[[value]].
    2. If registration’s installing worker installingWorker is not null, then:
      1. If the result of running Get Newest Worker with registration is installingWorker, invoke Clear Registration with registration and continue to the next iteration of the loop.
      2. Else, set registration’s installing worker to null.
    3. If registration’s waiting worker is not null, run the following substep in parallel:
      1. Invoke Activate with registration.

Unregister

Input
job, a job
Output
none
  1. If the origin of job’s scope url is not job’s client’s origin, then:
    1. Invoke Reject Job Promise with job and a "SecurityError" exception.
    2. Invoke Finish Job with job and abort these steps.
  2. Let registration be the result of running Get Registration algorithm passing job’s scope url as the argument.
  3. If registration is null, then:
    1. Invoke Resolve Job Promise with job and false.
    2. Invoke Finish Job with job and abort these steps.
  4. Set registration’s uninstalling flag.
  5. Invoke Resolve Job Promise with job and true.
  6. If no service worker client is using registration, then:
    1. If registration’s uninstalling flag is unset, invoke Finish Job with job and abort these steps.
    2. Invoke Clear Registration algorithm passing registration as its argument.

    When the registration is being used for a client, the deletion of the registration is handled by the Handle Service Worker Client Unload algorithm.

  7. Invoke Finish Job with job.

Set Registration

Input
scope, a URL
Output
registration, a service worker registration
  1. Run the following steps atomically.
  2. Let scopeString be serialized scope with the exclude fragment flag set.
  3. Let registration be a new service worker registration whose scope url is set to scope.
  4. Set a newly-created Record {[[key]]: scopeString, [[value]]: registration} to scope to registration map.
  5. Return registration.

Clear Registration

Input
registration, a service worker registration
Output
None
  1. Run the following steps atomically.
  2. Let redundantWorker be null.
  3. If registration’s installing worker is not null, then:
    1. Set redundantWorker to registration’s installing worker.
    2. Terminate redundantWorker.
    3. The user agent may abort in-flight requests triggered by redundantWorker.
    4. Run the Update Registration State algorithm passing registration, "installing" and null as the arguments.
    5. Run the Update Worker State algorithm passing redundantWorker and redundant as the arguments.
  4. If registration’s waiting worker is not null, then:
    1. Set redundantWorker to registration’s waiting worker.
    2. Terminate redundantWorker.
    3. The user agent may abort in-flight requests triggered by redundantWorker.
    4. Run the Update Registration State algorithm passing registration, "waiting" and null as the arguments.
    5. Run the Update Worker State algorithm passing redundantWorker and redundant as the arguments.
  5. If registration’s active worker is not null, then:
    1. Set redundantWorker to registration’s active worker.
    2. Terminate redundantWorker.
    3. The user agent may abort in-flight requests triggered by redundantWorker.
    4. Run the Update Registration State algorithm passing registration, "active" and null as the arguments.
    5. Run the Update Worker State algorithm passing redundantWorker and redundant as the arguments.
  6. Delete a Record {[[key]], [[value]]} entry from scope to registration map where registration’s scope url is the result of parsing entry.[[key]].

Update Registration State

Input
registration, a service worker registration
target, a string (one of "installing", "waiting", and "active")
source, a service worker or null
Output
None
  1. Let registrationObjects be an array containing all the ServiceWorkerRegistration objects associated with registration.
  2. If target is "installing", then:
    1. Set registration’s installing worker to source.
    2. For each registrationObject in registrationObjects:
      1. Queue a task to set the installing attribute of registrationObject to the ServiceWorker object that represents registration’s installing worker, or null if registration’s installing worker is null.
  3. Else if target is "waiting", then:
    1. Set registration’s waiting worker to source.
    2. For each registrationObject in registrationObjects:
      1. Queue a task to set the waiting attribute of registrationObject to the ServiceWorker object that represents registration’s waiting worker, or null if registration’s waiting worker is null.
  4. Else if target is "active", then:
    1. Set registration’s active worker to source.
    2. For each registrationObject in registrationObjects:
      1. Queue a task to set the active attribute of registrationObject to the ServiceWorker object that represents registration’s active worker, or null if registration’s active worker is null.

    The task must use registrationObject’s relevant settings object’s responsible event loop and the DOM manipulation task source.

Update Worker State

Input
worker, a service worker
state, a service worker’s state
Output
None
  1. Set worker’s state to state.
  2. Let workerObjects be an array containing all the ServiceWorker objects associated with worker.
  3. For each workerObject in workerObjects:
    1. Queue a task to run these substeps:
      1. Set the state attribute of workerObject to the value (in ServiceWorkerState enumeration) corresponding to the first matching statement, switching on worker’s state:
        installing
        "installing"

        The service worker in this state is considered an installing worker. During this state, event.waitUntil(f) can be called inside the oninstall event handler to extend the life of the installing worker until the passed promise resolves successfully. This is primarily used to ensure that the service worker is not active until all of the core caches are populated.

        installed
        "installed"

        The service worker in this state is considered a waiting worker.

        activating
        "activating"

        The service worker in this state is considered an active worker. During this state, event.waitUntil(f) can be called inside the onactivate event handler to extend the life of the active worker until the passed promise resolves successfully. No functional events are dispatched until the state becomes activated.

        activated
        "activated"

        The service worker in this state is considered an active worker ready to handle functional events.

        redundant
        "redundant"

        A new service worker is replacing the current service worker, or the current service worker is being discarded due to an install failure.

      2. Fire a simple event named statechange at workerObject.

    The task must use workerObject’s relevant settings object’s responsible event loop and the DOM manipulation task source.

Notify Controller Change

Input
client, a service worker client
Output
None
  1. Assert: client is not null.
  2. Queue a task to fire a simple event named controllerchange at the ServiceWorkerContainer object client is associated with.

The task must use client’s responsible event loop and the DOM manipulation task source.

Match Service Worker Registration

Input
clientURL, a URL
Output
registration, a service worker registration
  1. Run the following steps atomically.
  2. Let clientURLString be serialized clientURL.
  3. Let matchingScope be the empty string.
  4. Set matchingScope to the longest [[key]] in scope to registration map which the value of clientURLString starts with, if it exists.

    The URL string matching in this step is prefix-based rather than path-structural (e.g. a client URL string with "/prefix-of/resource.html" will match a registration for a scope with "/prefix").

  5. Let parsedMatchingScope be null.
  6. If matchingScope is not the empty string, set parsedMatchingScope to the result of parsing matchingScope.
  7. Let registration be the result of running Get Registration algorithm passing parsedMatchingScope as the argument.
  8. If registration is not null and registration’s uninstalling flag is set, return null.
  9. Return registration.

Match Service Worker for Foreign Fetch

Input
requestURL, a URL
Output
worker, a service worker
  1. Run the following steps atomically.
  2. Let registration be the result of running the Match Service Worker Registration algorithm passing requestURL as the argument.
  3. If registration is null, return null.
  4. Let worker be registration’s active worker.
  5. If worker is null, return null.
  6. Let requestURLString be the serialized requestURL.
  7. For each URL scope in worker’s list of foreign fetch scopes:
    1. Let scopeString be the serialized scope.
    2. If requestString starts with scopeString return worker.
  8. Return null.

Get Registration

Input
scope, a URL
Output
registration, a service worker registration
  1. Run the following steps atomically.
  2. Let scopeString be the empty string.
  3. If scope is not null, set scopeString to serialized scope with the exclude fragment flag set.
  4. Let registration be null.
  5. For each Record {[[key]], [[value]]} entry of its scope to registration map:
    1. If scopeString matches entry.[[key]], set registration to entry.[[value]].
  6. Return registration.

Get Newest Worker

Input
registration, a service worker registration
Output
worker, a service worker
  1. Run the following steps atomically.
  2. Let newestWorker be null.
  3. If registration’s installing worker is not null, set newestWorker to registration’s installing worker.
  4. Else if registration’s waiting worker is not null, set newestWorker to registration’s waiting worker.
  5. Else if registration’s active worker is not null, set newestWorker to registration’s active worker.
  6. Return newestWorker.

Create Client

Input
client, a service worker client
Output
clientObject, a Client object
  1. Let clientObject be a new Client object.
  2. Set clientObject’s service worker client to client.
  3. Return clientObject.

Create Window Client

Input
client, a service worker client
visibilityState, a string
focusState, a boolean
Output
windowClient, a WindowClient object
  1. Let windowClient be a new WindowClient object.
  2. Set windowClient’s service worker client to client.
  3. Set windowClient’s visibility state to visibilityState.
  4. Set windowClient’s focus state to focusState.
  5. Return windowClient.

Query Cache

Input
request, a Request object
options, a CacheQueryOptions object, optional
targetStorage, an array that has [Request, Response] pairs as its elements, optional
Output
resultArray, an array that has [Request, Response] pairs as its elements
  1. Let requestArray be an empty array.
  2. Let responseArray be an empty array.
  3. Let resultArray be an empty array.
  4. If options.ignoreMethod is false and request.method is neither "GET" nor "HEAD", return resultArray.
  5. Let cachedURL and requestURL be null.
  6. Let serializedCachedURL and serializedRequestURL be null.
  7. If the optional argument targetStorage is omitted, then:
    1. For each fetching record entry of its request to response map, in key insertion order:
      1. Set cachedURL to entry.[[key]]'s associated request’s url.
      2. Set requestURL to request’s associated request’s url.
      3. If options.ignoreSearch is true, then:
        1. Set cachedURL’s query to the empty string.
        2. Set requestURL’s query to the empty string.
      4. Set serializedCachedURL to serialized cachedURL.
      5. Set serializedRequestURL to serialized requestURL.
      6. If serializedCachedURL matches serializedRequestURL, then:
        1. Add a copy of entry.[[key]] to requestArray.
        2. Add a copy of entry.[[value]] to responseArray.
  8. Else:
    1. For each record in targetStorage:
      1. Set cachedURL to record[0]'s associated request’s url.
      2. Set requestURL to request’s associated request’s url.
      3. If options.ignoreSearch is true, then:
        1. Set cachedURL’s query to the empty string.
        2. Set requestURL’s query to the empty string.
      4. Set serializedCachedURL to serialized cachedURL.
      5. Set serializedRequestURL to serialized requestURL.
      6. If serializedCachedURL matches serializedRequestURL, then:
        1. Add record[0] to requestArray.
        2. Add record[1] to responseArray.
  9. For each cachedResponse in responseArray with the index index:
    1. Let cachedRequest be the indexth element in requestArray.
    2. If cachedResponse’s response’s header list contains no header named `Vary`, or options.ignoreVary is true, then:
      1. Add an array [cachedRequest, cachedResponse] to resultArray.
      2. Continue to the next iteration of the loop.
    3. Let varyHeaders be the array containing the elements corresponding to the field-values of the Vary header.
    4. Let matchFailed be false.
    5. For each f in varyHeaders:
      1. If f matches "*", or the result of running cachedRequest.headers object’s get(name) method with f as the argument does not match the result of running request.headers object’s get(name) method with f as the argument, then:
        1. Set matchFailed to true.
        2. Break the loop.
    6. If matchFailed is false, add an array [cachedRequest, cachedResponse] to resultArray.
  10. Return resultArray.

Batch Cache Operations

Input
operations, an array of CacheBatchOperation dictionary objects
Output
promise, a promise resolves with an array of Response objects.
  1. Let p be a promise resolved with no value.
  2. Return the result of transforming p with a fulfillment handler that performs the following substeps in parallel:
    1. Let itemsCopy be a new request to response map that is a copy of its context object’s request to response map.
    2. Let addedRecords be an empty array.
    3. Try running the following substeps atomically:
      1. Let resultArray be an empty array.
      2. For each operation in operations with the index index:
        1. If operation.type matches neither "delete" nor "put", throw a TypeError.
        2. If operation.type matches "delete" and operation.response is not null, throw a TypeError.
        3. If the result of running Query Cache algorithm passing operation.request, operation.options, and addedRecords as the arguments is not an empty array, throw an "InvalidStateError" exception.
        4. Let requestResponseArray be the result of running Query Cache algorithm passing operation.request and operation.options as the arguments.
        5. For each requestResponse in requestResponseArray:
          1. If operation.type matches "delete", remove the corresponding fetching record from request to response map.
        6. If operation.type matches "put", then:
          1. If operation.response is null, throw a TypeError.
          2. Let r be operation.request's associated request.
          3. If r’s url’s scheme is not one of "http" and "https", throw a TypeError.
          4. If r’s method is not `GET`, throw a TypeError.
          5. If operation.options is not null, throw a TypeError.
          6. If there exists a corresponding fetching record fetchingRecord for operation.request and operation.response in request to response map, set fetchingRecord.[[value]] to operation.response.
          7. Else, set a newly-created fetching record {[[key]]: operation.request, [[value]]: operation.response} to request to response map.

            The cache commit is allowed as long as the response’s headers are available.

          8. If the cache write operation in the previous two steps failed due to exceeding the granted quota limit, throw a "QuotaExceededError" exception.
          9. Add an array [operation.request, operation.response] to addedRecords.
        7. Add operation.response to resultArray.
      3. Return resultArray.
    4. And then, if an exception was thrown, then:
      1. Set the context object’s request to response map to itemsCopy.
      2. Throw the exception

Appendix B: Extended HTTP headers

Service Worker Script Request

An HTTP request to fetch a service worker’s script resource will include the following header:

`Service-Worker`
Indicates this request is a service worker’s script resource request.

This header helps administrators log the requests and detect threats.

Service Worker Script Response

An HTTP response to a service worker’s script resource request can include the following header:

`Service-Worker-Allowed`
Indicates the user agent will override the path restriction, which limits the maximum allowed scope url that the script can control, to the given value.

The value is a URL. If a relative URL is given, it is parsed against the script’s URL.

Default scope:
// Maximum allowed scope defaults to the path the script sits in
// "/js" in this example
navigator.serviceWorker.register("/js/sw.js").then(function() {
  console.log("Install succeeded with the default scope '/js'.");
});
Upper path without Service-Worker-Allowed header:
// Set the scope to an upper path of the script location
// Response has no Service-Worker-Allowed header
navigator.serviceWorker.register("/js/sw.js", { scope: "/" }).catch(function() {
  console.error("Install failed due to the path restriction violation.");
});
Upper path with Service-Worker-Allowed header:
// Set the scope to an upper path of the script location
// Response included "Service-Worker-Allowed : /"
navigator.serviceWorker.register("/js/sw.js", { scope: "/" }).then(function() {
  console.log("Install succeeded as the max allowed scope was overriden to '/'.");
});
A path restriction voliation even with Service-Worker-Allowed header:
// Set the scope to an upper path of the script location
// Response included "Service-Worker-Allowed : /foo"
navigator.serviceWorker.register("/foo/bar/sw.js", { scope: "/" }).catch(function() {
  console.error("Install failed as the scope is still out of the overriden maximum allowed scope.");
});

Syntax

ABNF for the values of the headers used by the service worker’s script resource requests and responses:

Service-Worker = %x73.63.72.69.70.74 ; "script", case-sensitive

The validation of the Service-Worker-Allowed header’s values is done by URL parsing algorithm (in Update algorithm) instead of using ABNF.

9. Acknowledgements

Deep thanks go to Andrew Betts for organizing and hosting a small workshop of like-minded individuals including: Jake Archibald, Jackson Gabbard, Tobie Langel, Robin Berjon, Patrick Lauke, Christian Heilmann. From the clarity of the day’s discussions and the use-cases outlined there, much has become possible. Further thanks to Andrew for raising consciousness about the offline problem. His organization of EdgeConf and inclusion of Offline as a persistent topic there has created many opportunities and connections that have enabled this work to progress.

Anne van Kesteren has generously lent his encyclopedic knowledge of Web Platform arcana and standards development experience throughout the development of the service worker. This specification would be incomplete without his previous work in describing the real-world behavior of URLs, HTTP Fetch, Promises, and DOM. Similarly, this specification would not be possible without Ian Hickson’s rigorous Web Worker spec. Much thanks to him.

In no particular order, deep gratitude for design guidance and discussion goes to: Jungkee Song, Alec Flett, David Barrett-Kahn, Aaron Boodman, Michael Nordman, Tom Ashworth, Kinuko Yasuda, Darin Fisher, Jonas Sicking, Jesús Leganés Combarro, Mark Christian, Dave Hermann, Yehuda Katz, François Remy, Ilya Grigorik, Will Chan, Domenic Denicola, Nikhil Marathe, Yves Lafon, Adam Barth, Greg Simon, Devdatta Akhawe, Dominic Cooney, Jeffrey Yasskin, Joshua Bell, Boris Zbarsky, Matt Falkenhagen, Tobie Langel, Gavin Peters, Ben Kelly, Hiroki Nakagawa, Jake Archibald, Josh Soref and Jinho Bang.

Jason Weber, Chris Wilson, Paul Kinlan, Ehsan Akhgari, and Daniel Austin have provided valuable, well-timed feedback on requirements and the standardization process.

The authors would also like to thank Dimitri Glazkov for his scripts and formatting tools which have been essential in the production of this specification. The authors are also grateful for his considerable guidance.

Thanks also to Vivian Cromwell, Greg Simon, Alex Komoroske, Wonsuk Lee, and Seojin Kim for their considerable professional support.

Conformance

Document conventions

Conformance requirements are expressed with a combination of descriptive assertions and RFC 2119 terminology. The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in the normative parts of this document are to be interpreted as described in RFC 2119. However, for readability, these words do not appear in all uppercase letters in this specification.

All of the text of this specification is normative except sections explicitly marked as non-normative, examples, and notes. [RFC2119]

Examples in this specification are introduced with the words “for example” or are set apart from the normative text with class="example", like this:

This is an example of an informative example.

Informative notes begin with the word “Note” and are set apart from the normative text with class="note", like this:

Note, this is an informative note.

Conformant Algorithms

Requirements phrased in the imperative as part of algorithms (such as "strip any leading space characters" or "return false and abort these steps") are to be interpreted with the meaning of the key word ("must", "should", "may", etc) used in introducing the algorithm.

Conformance requirements phrased as algorithms or specific steps can be implemented in any manner, so long as the end result is equivalent#dfn-processing-equivalenceReferenced in:3.1.3. postMessage(message, transfer)3.2.5. update()3.2.6. unregister()3.4.1. controller3.4.2. ready (2)3.4.3. register(scriptURL, options)3.4.4. getRegistration(clientURL)3.4.5. getRegistrations()4.1.3. skipWaiting() (2)4.2.4. postMessage(message, transfer)4.2.7. focus() (2)4.2.8. navigate(url) (2)4.3.1. get(id) (2) (3)4.3.2. matchAll(options) (2) (3) (4) (5)4.3.3. openWindow(url) (2)4.3.4. claim()4.4.1. event.waitUntil(f) (2)4.5.1. event.registerForeignFetch(options)4.6.4. event.respondWith(r)4.7.2. event.respondWith(r)5.4.1. match(request, options)5.4.2. matchAll(request, options)5.4.3. add(request)5.4.4. addAll(requests)5.4.5. put(request, response)5.4.6. delete(request, options)5.4.7. keys(request, options)5.5.1. match(request, options)5.5.2. has(cacheName)5.5.3. open(cacheName)5.5.4. delete(cacheName)5.5.5. keys()8.4. Request Functional Event DispatchRegisterUpdateInstall (2)Handle Fetch (2) (3) (4)Handle Functional EventHandle Service Worker Client Unload (2). In particular, the algorithms defined in this specification are intended to be easy to understand and are not intended to be performant. Implementers are encouraged to optimize.

Index

Terms defined by this specification

Terms defined by reference

References

Normative References

[CSP2]
Mike West; Adam Barth; Daniel Veditz. Content Security Policy Level 2. 21 July 2015. CR. URL: https://w3c.github.io/webappsec/specs/CSP2/
[ECMA-262]
ECMAScript Language Specification. URL: https://tc39.github.io/ecma262/
[FETCH]
Anne van Kesteren. Fetch Standard. Living Standard. URL: https://fetch.spec.whatwg.org/
[HTML]
Ian Hickson. HTML Standard. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[WHATWG-DOM]
Anne van Kesteren. DOM Standard. Living Standard. URL: https://dom.spec.whatwg.org/
[WHATWG-URL]
Anne van Kesteren; Sam Ruby. URL Standard. Living Standard. URL: https://url.spec.whatwg.org/
[WebIDL]
Cameron McCormack; Boris Zbarsky. WebIDL Level 1. 4 August 2015. WD. URL: https://heycam.github.io/webidl/
[PAGE-VISIBILITY]
Jatinder Mann; Arvind Jain. Page Visibility (Second Edition). 29 October 2013. REC. URL: http://www.w3.org/TR/page-visibility/
[POWERFUL-FEATURES]
Mike West; Yan Zhu. Privileged Contexts. 24 April 2015. WD. URL: https://w3c.github.io/webappsec/specs/powerfulfeatures/
[PROMISES-GUIDE]
Writing Promise-Using Specifications. 24 July 2015. Finding of the W3C TAG. URL: https://www.w3.org/2001/tag/doc/promises-guide
[QUOTA-API]
Kinuko Yasuda. Quota Management API. 15 December 2015. WD. URL: http://www.w3.org/TR/quota-api/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
[RFC5234]
D. Crocker, Ed.; P. Overell. Augmented BNF for Syntax Specifications: ABNF. January 2008. Internet Standard. URL: https://tools.ietf.org/html/rfc5234
[RFC7230]
R. Fielding, Ed.; J. Reschke, Ed.. Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing. June 2014. Proposed Standard. URL: https://tools.ietf.org/html/rfc7230
[RFC7231]
R. Fielding, Ed.; J. Reschke, Ed.. Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content. June 2014. Proposed Standard. URL: https://tools.ietf.org/html/rfc7231

Informative References

[WHATWG-NOTIFICATIONS]
Anne van Kesteren. Notifications API Standard. Living Standard. URL: https://notifications.spec.whatwg.org/
[UNSANCTIONED-TRACKING]
Unsanctioned Web Tracking. 17 July 2015. Finding of the W3C TAG. URL: https://www.w3.org/2001/tag/doc/unsanctioned-tracking

IDL Index

[Exposed=(Window,Worker)]
interface ServiceWorker : EventTarget {
  readonly attribute USVString scriptURL;
  readonly attribute ServiceWorkerState state;
  void postMessage(any message, optional sequence<Transferable> transfer);

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

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

[Exposed=(Window,Worker)]
interface ServiceWorkerRegistration : EventTarget {
  [Unforgeable] readonly attribute ServiceWorker? installing;
  [Unforgeable] readonly attribute ServiceWorker? waiting;
  [Unforgeable] readonly attribute ServiceWorker? active;

  readonly attribute USVString scope;

  [NewObject] Promise<void> update();
  [NewObject] Promise<boolean> unregister();

  // event
  attribute EventHandler onupdatefound;
};

partial interface Navigator {
  [SecureContext, SameObject] readonly attribute ServiceWorkerContainer serviceWorker;
};

partial interface WorkerNavigator {
  [SecureContext, SameObject] readonly attribute ServiceWorkerContainer serviceWorker;
};

[SecureContext, Exposed=(Window,Worker)]
interface ServiceWorkerContainer : EventTarget {
  [Unforgeable] readonly attribute ServiceWorker? controller;
  [SameObject] readonly attribute Promise<ServiceWorkerRegistration> ready;

  [NewObject] Promise<ServiceWorkerRegistration> register(USVString scriptURL, optional RegistrationOptions options);

  [NewObject] Promise<any> getRegistration(optional USVString clientURL = "");
  [NewObject] Promise<sequence<ServiceWorkerRegistration>> getRegistrations();


  // events
  attribute EventHandler oncontrollerchange;
  attribute EventHandler onerror;
  attribute EventHandler onmessage; // event.source of message events is ServiceWorker object
};

dictionary RegistrationOptions {
  USVString scope;
  WorkerType type = "classic";
};

[Constructor(DOMString type, optional ServiceWorkerMessageEventInit eventInitDict), Exposed=(Window,Worker)]
interface ServiceWorkerMessageEvent : Event {
  readonly attribute any data;
  readonly attribute DOMString origin;
  readonly attribute DOMString lastEventId;
  [SameObject] readonly attribute (ServiceWorker or MessagePort)? source;
  readonly attribute FrozenArray<MessagePort>? ports;
};

dictionary ServiceWorkerMessageEventInit : EventInit {
  any data;
  DOMString origin;
  DOMString lastEventId;
  (ServiceWorker or MessagePort)? source;
  sequence<MessagePort>? ports;
};

[Global=(Worker,ServiceWorker), Exposed=ServiceWorker]
interface ServiceWorkerGlobalScope : WorkerGlobalScope {
  // A container for a list of Client objects that correspond to
  // browsing contexts (or shared workers) that are on the origin of this SW
  [SameObject] readonly attribute Clients clients;
  [SameObject] readonly attribute ServiceWorkerRegistration registration;

  [NewObject] Promise<void> skipWaiting();

  attribute EventHandler oninstall;
  attribute EventHandler onactivate;
  attribute EventHandler onfetch;
  attribute EventHandler onforeignfetch;

  // event
  attribute EventHandler onmessage; // event.source of the message events is Client object
};

[Exposed=ServiceWorker]
interface Client {
  readonly attribute USVString url;
  readonly attribute FrameType frameType;
  readonly attribute DOMString id;
  void postMessage(any message, optional sequence<Transferable> transfer);
};

[Exposed=ServiceWorker]
interface WindowClient : Client {
  readonly attribute VisibilityState visibilityState;
  readonly attribute boolean focused;
  [NewObject] Promise<WindowClient> focus();
  [NewObject] Promise<WindowClient> navigate(USVString url);
};

enum FrameType {
  "auxiliary",
  "top-level",
  "nested",
  "none"
};

[Exposed=ServiceWorker]
interface Clients {
  // The objects returned will be new instances every time
  [NewObject] Promise<any> get(DOMString id);
  [NewObject] Promise<sequence<Client>> matchAll(optional ClientQueryOptions options);
  [NewObject] Promise<WindowClient?> openWindow(USVString url);
  [NewObject] Promise<void> claim();
};

dictionary ClientQueryOptions {
  boolean includeUncontrolled = false;
  ClientType type = "window";
};

enum ClientType {
  "window",
  "worker",
  "sharedworker",
  "all"
};

[Constructor(DOMString type, optional ExtendableEventInit eventInitDict), Exposed=ServiceWorker]
interface ExtendableEvent : Event {
  void waitUntil(Promise<any> f);
};

dictionary ExtendableEventInit : EventInit {
  // Defined for the forward compatibility across the derived events
};

[Constructor(DOMString type, optional ExtendableEventInit eventInitDict), Exposed=ServiceWorker]
interface InstallEvent : ExtendableEvent {
  void registerForeignFetch(ForeignFetchOptions options);
};

dictionary ForeignFetchOptions {
  required sequence<USVString> scopes;
  required sequence<USVString> origins;
};

[Constructor(DOMString type, FetchEventInit eventInitDict), Exposed=ServiceWorker]
interface FetchEvent : ExtendableEvent {
  [SameObject] readonly attribute Request request;
  readonly attribute DOMString? clientId;
  readonly attribute boolean isReload;

  void respondWith(Promise<Response> r);
};

dictionary FetchEventInit : ExtendableEventInit {
  required Request request;
  DOMString? clientId = null;
  boolean isReload = false;
};

[Constructor(DOMString type, ForeignFetchEventInit eventInitDict), Exposed=ServiceWorker]
interface ForeignFetchEvent : ExtendableEvent {
  [SameObject] readonly attribute Request request;

  void respondWith(Promise<ForeignFetchResponse> r);
};

dictionary ForeignFetchEventInit : ExtendableEventInit {
  required Request request;
};

dictionary ForeignFetchResponse {
  required Response response;
  USVString origin;
  sequence<ByteString> headers;
};

[Constructor(DOMString type, optional ExtendableMessageEventInit eventInitDict), Exposed=ServiceWorker]
interface ExtendableMessageEvent : ExtendableEvent {
  readonly attribute any data;
  readonly attribute DOMString origin;
  readonly attribute DOMString lastEventId;
  [SameObject] readonly attribute (Client or ServiceWorker or MessagePort)? source;
  readonly attribute FrozenArray<MessagePort>? ports;
};

dictionary ExtendableMessageEventInit : ExtendableEventInit {
  any data;
  DOMString origin;
  DOMString lastEventId;
  (Client or ServiceWorker or MessagePort)? source;
  sequence<MessagePort>? ports;
};

partial interface Window {
  [SecureContext, SameObject] readonly attribute CacheStorage caches;
};

partial interface WorkerGlobalScope {
  [SecureContext, SameObject] readonly attribute CacheStorage caches;
};

[Exposed=(Window,Worker)]
interface Cache {
  [NewObject] Promise<any> match(RequestInfo request, optional CacheQueryOptions options);
  [NewObject] Promise<sequence<Response>> matchAll(optional RequestInfo request, optional CacheQueryOptions options);
  [NewObject] Promise<void> add(RequestInfo request);
  [NewObject] Promise<void> addAll(sequence<RequestInfo> requests);
  [NewObject] Promise<void> put(RequestInfo request, Response response);
  [NewObject] Promise<boolean> delete(RequestInfo request, optional CacheQueryOptions options);
  [NewObject] Promise<sequence<Request>> keys(optional RequestInfo request, optional CacheQueryOptions options);
};

dictionary CacheQueryOptions {
  boolean ignoreSearch = false;
  boolean ignoreMethod = false;
  boolean ignoreVary = false;
  DOMString cacheName;
};

dictionary CacheBatchOperation {
  DOMString type;
  Request request;
  Response response;
  CacheQueryOptions options;
};

[SecureContext, Exposed=(Window,Worker)]
interface CacheStorage {
  [NewObject] Promise<any> match(RequestInfo request, optional CacheQueryOptions options);
  [NewObject] Promise<boolean> has(DOMString cacheName);
  [NewObject] Promise<Cache> open(DOMString cacheName);
  [NewObject] Promise<boolean> delete(DOMString cacheName);
  [NewObject] Promise<sequence<DOMString>> keys();
};

Issues Index

These substeps will be replaced by using pipe when the algorithm for pipeTo becomes stable.
These substeps will be replaced by using pipe when the algorithm for pipeTo becomes stable.
Remove this definition after sorting out the referencing sites.
This needs an extra step in the HTTP fetch algorithm in between step 3 and 4, to call this algorithm for all requests if response is null at that point.