### Service worker caching with install and fetch handlers Source: https://www.w3.org/TR/service-workers Service worker caching example from the "Serving Cached Resources" section. The install handler opens a cache named "shell-v1" and adds a list of resources; the fetch handler responds with a cached match, falls back to the network, and finally to "/fallback.html" on error. ```javascript // caching.js self.addEventListener("install", event => { event.waitUntil( // Open a cache of resources. caches.open("shell-v1").then(cache => { // Begins the process of fetching them. Succeeds only once all // resources have been stored. Even just one failing resource // causes the entire operation to fail. return cache.addAll([ "/app.html", "/assets/v1/base.css", "/assets/v1/app.js", "/assets/v1/logo.png", "/assets/v1/intro_video.webm" ]); }) ); }); self.addEventListener("fetch", event => { // 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: event.respondWith( caches.match(e.request).then(response => { return response || fetch(e.request); }).catch(() => { return caches.match("/fallback.html"); }) ); }); ``` -------------------------------- ### InstallEvent.addRoutes(rules) Source: https://www.w3.org/TR/service-workers Adds routing rules for the install event. ```APIDOC ## [POST] InstallEvent.addRoutes(rules) ### Description Adds routing rules for the install event. ### Method POST ### Endpoint InstallEvent.addRoutes(rules) ### Parameters #### Request Body - **rules** (sequence) - Required - The routing rules to add. ``` -------------------------------- ### ServiceWorkerRegistration.installing Source: https://www.w3.org/TR/service-workers Retrieves the installing service worker of the registration. ```APIDOC ## [GET] ServiceWorkerRegistration.installing ### Description Returns the installing service worker, if any. ### Method GET ### Endpoint ServiceWorkerRegistration.installing ### Response #### Success Response (200) - **installing** (ServiceWorker?) - The installing service worker or null. ``` -------------------------------- ### InstallEvent.addRoutes() Source: https://www.w3.org/TR/service-workers Method to add routing rules during the install event. ```APIDOC ## InstallEvent.addRoutes(rules) ### Description Adds routing rules for the service worker. ### Parameters - **rules** ((RouterRule or sequence)) - Required - The routing rules to add. ### Returns - **Promise** - Resolves when the rules are added. ``` -------------------------------- ### Register a service worker and post a message to the installing worker Source: https://www.w3.org/TR/service-workers Registers a service worker with the default scope (the script's directory, here "/"). The promise resolves with a registration object; if the worker is still installing, it posts a message to it. On failure, logs an error. ```javascript // scope defaults to the path the script sits in // "/" in this example navigator.serviceWorker.register("/serviceworker.js").then(registration => { console.log("success!"); if (registration.installing) { registration.installing.postMessage("Howdy from your installing page."); } }, err => { console.error("Installing the worker failed!", err); }); ``` -------------------------------- ### POST ServiceWorkerContainer.startMessages Source: https://www.w3.org/TR/service-workers The `startMessages` method starts dispatching messages from the client message queue to the service worker. ```APIDOC ## [POST] ServiceWorkerContainer.startMessages ### Description Starts dispatching messages from the client message queue to the service worker. ### Method POST ### Endpoint ServiceWorkerContainer.startMessages ### Response #### Success Response (200) - **undefined** (undefined) - This method returns `undefined`. #### Response Example ``` undefined ``` ``` -------------------------------- ### ServiceWorkerContainer.startMessages() Source: https://www.w3.org/TR/service-workers Starts the dispatching of messages from the service worker. ```APIDOC ## [POST] ServiceWorkerContainer.startMessages() ### Description Starts dispatching messages from the service worker. ### Method POST ### Endpoint ServiceWorkerContainer.startMessages() ``` -------------------------------- ### Clients.openWindow(url) Source: https://www.w3.org/TR/service-workers Opens a new window with the given URL. ```APIDOC ## [POST] Clients.openWindow(url) ### Description Opens a new window with the given URL. ### Method POST ### Endpoint Clients.openWindow(url) ### Parameters #### Request Body - **url** (USVString) - Required - The URL to open. ### Response #### Success Response (200) - **promise** (Promise) - Resolves with the new client or null. ``` -------------------------------- ### WindowClient.focus() and navigate() Source: https://www.w3.org/TR/service-workers Methods to control a window client. ```APIDOC ## WindowClient.focus() ### Description Focuses the window client. ### Returns - **Promise** - Resolves with the focused window client. ``` ```APIDOC ## WindowClient.navigate(url) ### Description Navigates the window client to the specified URL. ### Parameters - **url** (USVString) - Required - The URL to navigate to. ### Returns - **Promise** - Resolves with the window client or null if navigation fails. ``` -------------------------------- ### Clients.openWindow(url) Source: https://www.w3.org/TR/service-workers Opens a new window for the given URL. ```APIDOC ## [POST] Clients.openWindow(url) ### Description Opens a new window with the given URL and returns a promise that resolves with a WindowClient or null. ### Method POST ### Endpoint Clients.openWindow(url) ### Parameters #### Path Parameters - **url** (USVString) - Required - The URL to open. ### Response #### Success Response (200) - **windowClient** (WindowClient or null) - The opened window client, or null if not allowed. #### Response Example { "windowClient": {} } ``` -------------------------------- ### GET /clients Source: https://www.w3.org/TR/service-workers The `clients` getter returns the `Clients` object associated with the `ServiceWorkerGlobalScope`. ```APIDOC ## [GET] /clients ### Description Returns the `Clients` object associated with the `ServiceWorkerGlobalScope`. ### Method GET ### Endpoint /clients ### Response #### Success Response (200) - **clients** (Clients) - The `Clients` object associated with this. #### Response Example ```json { "clients": {} } ``` ``` -------------------------------- ### GET navigator.serviceWorker Source: https://www.w3.org/TR/service-workers The `serviceWorker` getter returns the `ServiceWorkerContainer` object associated with the `Navigator` or `WorkerNavigator` object. ```APIDOC ## [GET] navigator.serviceWorker ### Description Returns the `ServiceWorkerContainer` object associated with the `Navigator` or `WorkerNavigator` object. ### Method GET ### Endpoint navigator.serviceWorker ### Response #### Success Response (200) - **serviceWorker** (ServiceWorkerContainer) - The associated `ServiceWorkerContainer` object. #### Response Example ``` ServiceWorkerContainer ``` ``` -------------------------------- ### POST /navigate Source: https://www.w3.org/TR/service-workers The `navigate()` method navigates the window client to the specified URL and returns a promise that resolves with the navigated `WindowClient` or null. ```APIDOC ## [POST] /navigate ### Description Navigates the window client to the specified URL. ### Method POST ### Endpoint /navigate ### Parameters #### Request Body - **url** (USVString) - Required - The URL to navigate to. ### Response #### Success Response (200) - **promise** (Promise) - Resolves with the navigated `WindowClient` or null. #### Response Example ```json { "promise": {} } ``` ``` -------------------------------- ### Clients.matchAll(options) Source: https://www.w3.org/TR/service-workers Returns all client objects that match the given options. ```APIDOC ## [GET] Clients.matchAll(options) ### Description Returns a promise that resolves with an array of Client objects matching the given options. ### Method GET ### Endpoint Clients.matchAll(options) ### Parameters #### Query Parameters - **options** (ClientQueryOptions) - Optional - An object with includeUncontrolled (boolean) and type (ClientType). ### Response #### Success Response (200) - **clients** (FrozenArray) - The matching clients. #### Response Example { "clients": [] } ``` -------------------------------- ### openWindow(url) Source: https://www.w3.org/TR/service-workers The openWindow(url) method opens a new top-level browsing context and navigates it to the given URL, then resolves with the resulting WindowClient or null if the storage key does not match. ```APIDOC ## openWindow(url) ### Description Opens a new top-level browsing context and navigates it to the given URL, then resolves with the resulting WindowClient or null if the storage key does not match. ### Method openWindow ### Parameters - **url** (string) - Required - The URL to open in the new window. ### Returns - Promise resolving to a WindowClient or null. ### Exceptions - TypeError - If the URL cannot be parsed or is about:blank. - InvalidAccessError - If no Window in this origin has transient activation. ``` -------------------------------- ### GET ServiceWorkerContainer.getRegistrations Source: https://www.w3.org/TR/service-workers The `getRegistrations` method returns a promise that resolves with a frozen array of all `ServiceWorkerRegistration` objects for the client. ```APIDOC ## [GET] ServiceWorkerContainer.getRegistrations ### Description Returns a promise that resolves with a frozen array of all `ServiceWorkerRegistration` objects for the client. ### Method GET ### Endpoint ServiceWorkerContainer.getRegistrations ### Response #### Success Response (200) - **registrations** (Promise>) - A promise that resolves with an array of registrations. #### Response Example ``` Promise> ``` ``` -------------------------------- ### Clients.matchAll(options) Source: https://www.w3.org/TR/service-workers Retrieves all clients matching the given options. ```APIDOC ## [GET] Clients.matchAll(options) ### Description Gets all matching clients. ### Method GET ### Endpoint Clients.matchAll(options) ### Parameters #### Query Parameters - **options** (ClientQueryOptions) - Optional - Query options. ### Response #### Success Response (200) - **promise** (Promise>) - Resolves with a list of clients. ``` -------------------------------- ### GET /serviceWorker Source: https://www.w3.org/TR/service-workers The `serviceWorker` getter returns the service worker object that represents this service worker in the relevant settings object. ```APIDOC ## [GET] /serviceWorker ### Description Returns the service worker object that represents this service worker in the relevant settings object. ### Method GET ### Endpoint /serviceWorker ### Response #### Success Response (200) - **serviceWorker** (ServiceWorker) - The service worker object. #### Response Example ```json { "serviceWorker": {} } ``` ``` -------------------------------- ### GET ServiceWorkerContainer.getRegistration Source: https://www.w3.org/TR/service-workers The `getRegistration` method returns a promise that resolves with the `ServiceWorkerRegistration` for the given client URL, or `undefined` if none is found. ```APIDOC ## [GET] ServiceWorkerContainer.getRegistration ### Description Returns a promise that resolves with the `ServiceWorkerRegistration` for the given client URL, or `undefined` if none is found. ### Method GET ### Endpoint ServiceWorkerContainer.getRegistration ### Parameters #### Query Parameters - **clientURL** (USVString) - Optional - The URL of the client (default: ""). ### Response #### Success Response (200) - **registration** (Promise<(ServiceWorkerRegistration or undefined)>) - A promise that resolves with the registration or `undefined`. #### Response Example ``` Promise ``` ``` -------------------------------- ### startMessages() Source: https://www.w3.org/TR/service-workers The startMessages method enables the client message queue. ```APIDOC ## startMessages() ### Description Enables the client message queue if it is not already enabled. ### Method startMessages ### Parameters None. ### Returns Void. ``` -------------------------------- ### POST /focus Source: https://www.w3.org/TR/service-workers The `focus()` method focuses the window client and returns a promise that resolves with the focused `WindowClient`. ```APIDOC ## [POST] /focus ### Description Focuses the window client. ### Method POST ### Endpoint /focus ### Response #### Success Response (200) - **promise** (Promise) - Resolves with the focused `WindowClient`. #### Response Example ```json { "promise": {} } ``` ``` -------------------------------- ### GET ServiceWorkerContainer.ready Source: https://www.w3.org/TR/service-workers The `ready` attribute returns a promise that resolves with a `ServiceWorkerRegistration` when there is an active service worker for the client. The promise never rejects. ```APIDOC ## [GET] ServiceWorkerContainer.ready ### Description Returns a promise that resolves with a `ServiceWorkerRegistration` when there is an active service worker for the client. The promise never rejects. ### Method GET ### Endpoint ServiceWorkerContainer.ready ### Response #### Success Response (200) - **ready** (Promise) - A promise that resolves with the registration when an active worker is available. #### Response Example ``` Promise ``` ``` -------------------------------- ### GET ServiceWorkerContainer.controller Source: https://www.w3.org/TR/service-workers The `controller` attribute returns the `ServiceWorker` object representing the active service worker for the client, or `null` if there is no active service worker. ```APIDOC ## [GET] ServiceWorkerContainer.controller ### Description Returns the `ServiceWorker` object that represents the active service worker of the client, or `null` if there is no active service worker. ### Method GET ### Endpoint ServiceWorkerContainer.controller ### Response #### Success Response (200) - **controller** (ServiceWorker or null) - The active service worker object, or `null` if none. #### Response Example ``` ServiceWorker | null ``` ``` -------------------------------- ### enable() Source: https://www.w3.org/TR/service-workers Enables navigation preload for the associated service worker registration. ```APIDOC ## [enable()] ### Description Enables navigation preload for the associated service worker registration. Returns a promise that resolves with undefined, or rejects with an InvalidStateError if the registration has no active worker. ### Method enable() ### Parameters None. ### Response #### Success Response - **undefined** - Resolves with undefined when navigation preload is enabled. #### Error Response - **InvalidStateError** - Rejects with an InvalidStateError DOMException if the registration's active worker is null. ### Response Example ``` undefined ``` ``` -------------------------------- ### Client.navigate(url) Source: https://www.w3.org/TR/service-workers Navigates the client to the given URL. ```APIDOC ## [POST] Client.navigate(url) ### Description Navigates the client to a URL. ### Method POST ### Endpoint Client.navigate(url) ### Parameters #### Request Body - **url** (USVString) - Required - The URL to navigate to. ### Response #### Success Response (200) - **promise** (Promise) - Resolves with the navigated client or null. ``` -------------------------------- ### GET /registration Source: https://www.w3.org/TR/service-workers The `registration` getter returns the service worker registration object representing this service worker's containing service worker registration. ```APIDOC ## [GET] /registration ### Description Returns the service worker registration object representing this service worker's containing service worker registration. ### Method GET ### Endpoint /registration ### Response #### Success Response (200) - **registration** (ServiceWorkerRegistration) - The service worker registration object. #### Response Example ```json { "registration": {} } ``` ``` -------------------------------- ### open(cacheName) Source: https://www.w3.org/TR/service-workers Opens a cache by name, returning a Cache object. If the cache does not exist, it is created. Rejects with QuotaExceededError if quota is exceeded. ```APIDOC ## open(cacheName) ### Description Opens a Cache object for the given cache name. If a cache with that name already exists, it returns a new Cache object representing that cache; otherwise, it creates a new cache and returns a Cache object for it. ### Method open ### Parameters - **cacheName** (string) - Required - The name of the cache to open. ### Returns A Promise that resolves with a new Cache object representing the cache. ### Errors - **QuotaExceededError** - Rejects the promise if the cache write operation fails due to exceeding the granted quota limit. ``` -------------------------------- ### POST /serviceworker.js Source: https://www.w3.org/TR/service-workers Registers a service worker script with the browser. The registration returns a promise that resolves to a ServiceWorkerRegistration object. The scope defaults to the path the script sits in (e.g., "/" in the example). ```APIDOC ## [POST] /serviceworker.js ### Description Registers a service worker script with the browser. The registration returns a promise that resolves to a ServiceWorkerRegistration object. The scope defaults to the path the script sits in (e.g., "/" in the example). ### Method POST ### Endpoint /serviceworker.js ### Parameters #### Request Body - **scriptURL** (string) - Required - The URL of the service worker script to register. ### Request Example ``` navigator.serviceWorker.register("/serviceworker.js") ``` ### Response #### Success Response (200) - **registration** (ServiceWorkerRegistration) - The registration object for the service worker. #### Response Example ``` registration = { installing: ServiceWorker, // ... } ``` ``` -------------------------------- ### navigate(url) Source: https://www.w3.org/TR/service-workers Navigates the client to the specified URL. Returns a promise that resolves with a WindowClient or null. ```APIDOC ## [POST] navigate(url) ### Description Navigates the client to the given URL. Resolves with a WindowClient or null if the navigation is cross-origin. ### Method POST ### Endpoint navigate(url) ### Parameters #### Path Parameters - **url** (USVString) - Required - The URL to navigate to. ### Response #### Success Response (200) - **windowClient** (WindowClient or null) - The resulting client, or null if cross-origin. #### Error Response - **TypeError** - If the URL is invalid, about:blank, or the client is not controlled by the service worker. #### Response Example { "windowClient": {} } ``` -------------------------------- ### ServiceWorkerGlobalScope interface definition Source: https://www.w3.org/TR/service-workers WebIDL definition of the ServiceWorkerGlobalScope interface, representing the global execution context of a service worker. It exposes clients, registration, serviceWorker, skipWaiting(), and event handlers for install, activate, fetch, message, and messageerror. ```webidl [Global=(Worker,ServiceWorker), Exposed=ServiceWorker, SecureContext] interface ServiceWorkerGlobalScope : WorkerGlobalScope { [SameObject] readonly attribute Clients clients; [SameObject] readonly attribute ServiceWorkerRegistration registration; [SameObject] readonly attribute ServiceWorker serviceWorker; [NewObject] Promise skipWaiting(); attribute EventHandler oninstall; attribute EventHandler onactivate; attribute EventHandler onfetch; attribute EventHandler onmessage; attribute EventHandler onmessageerror; }; ``` -------------------------------- ### InstallEvent.addRoutes(rules) Source: https://www.w3.org/TR/service-workers Documentation for the addRoutes(rules) method of the InstallEvent interface, which adds routing rules to the service worker. ```APIDOC ## [EVENT] addRoutes(rules) ### Description Adds routing rules to the service worker. This method is available on the InstallEvent interface. ### Method addRoutes(rules) ### Parameters - **rules** (RouterRule or sequence) - Required - The routing rules to add. ### Returns - **Promise** - A promise that resolves when the routes are added. ### RouterRule Dictionary - **condition** (RouterCondition) - Required - The condition that must match for the rule to apply. - **source** (RouterSource) - Required - The source that handles the matched request. ### RouterCondition Dictionary - **urlPattern** (URLPatternCompatible) - Optional - The URL pattern to match. - **requestMethod** (ByteString) - Optional - The HTTP method to match. - **requestMode** (RequestMode) - Optional - The request mode to match. - **requestDestination** (RequestDestination) - Optional - The request destination to match. - **runningStatus** (RunningStatus) - Optional - The running status of the service worker to match. - **_or** (sequence) - Optional - A list of conditions where at least one must match. - **not** (RouterCondition) - Optional - A condition that must not match. ### RouterSource Type - **RouterSourceDict** - An object with a `cacheName` property (DOMString). - **RouterSourceEnum** - One of: "cache", "fetch-event", "network", "race-network-and-fetch-handler". ``` -------------------------------- ### focus() Source: https://www.w3.org/TR/service-workers Focuses the client. Returns a promise that resolves with the WindowClient if successful. ```APIDOC ## [POST] focus() ### Description Attempts to focus the client. Requires transient activation. Resolves with the WindowClient if focused, otherwise rejects with a TypeError. ### Method POST ### Endpoint focus() ### Response #### Success Response (200) - **windowClient** (WindowClient) - The focused client. #### Error Response - **InvalidAccessError** - If no Window in this origin has transient activation. - **TypeError** - If the client could not be focused. #### Response Example { "windowClient": {} } ``` -------------------------------- ### matchAll(options) Source: https://www.w3.org/TR/service-workers Documentation for the matchAll(options) method of the Clients interface in the Service Workers API. ```APIDOC ## matchAll(options) ### Description Returns a promise that resolves with an array of Client objects matching the given options, representing the service worker clients controlled by the service worker. ### Method matchAll ### Parameters #### Options - **includeUncontrolled** (boolean) - Optional - If false, only include clients whose active service worker is the associated service worker. - **type** (string) - Optional - Can be "window", "worker", "sharedworker", or "all". Determines which types of clients to match. ### Return Value A promise that resolves with a frozen array of Client objects (WindowClient for window clients, Client for worker clients). ### Behavior - Only clients with the same storage key as the service worker's registration are considered. - Clients that are not secure contexts or have their execution ready flag unset or discarded flag set are skipped. - Window clients are sorted first, with focused windows first, then by creation order. Worker clients are placed after window clients. ### Example ```js const clients = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); ``` ``` -------------------------------- ### Client.focus() Source: https://www.w3.org/TR/service-workers Focuses the client and returns a promise resolving to the client. ```APIDOC ## [POST] Client.focus() ### Description Focuses the client. ### Method POST ### Endpoint Client.focus() ### Response #### Success Response (200) - **promise** (Promise) - Resolves with the focused client. ``` -------------------------------- ### FetchEvent Interface Source: https://www.w3.org/TR/service-workers Documentation for the FetchEvent interface, including its constructor, attributes, and methods. ```APIDOC ## FetchEvent Interface ### Description The FetchEvent interface represents a fetch event dispatched to a service worker. It extends the ExtendableEvent interface and provides properties and methods for handling fetch requests. ### Interface Definition ``` [Exposed=ServiceWorker] interface FetchEvent : ExtendableEvent { constructor(DOMString type, FetchEventInit eventInitDict); [SameObject] readonly attribute Request request; readonly attribute Promise preloadResponse; readonly attribute DOMString clientId; readonly attribute DOMString resultingClientId; readonly attribute DOMString replacesClientId; readonly attribute Promise handled; undefined respondWith(Promise r); }; ``` ### Dictionary Definition ``` dictionary FetchEventInit : ExtendableEventInit { required Request request; Promise preloadResponse; DOMString clientId = ""; DOMString resultingClientId = ""; DOMString replacesClientId = ""; Promise handled; }; ``` ### Attributes - **request** (Request) - Read-only. The request that triggered the fetch event. - **preloadResponse** (Promise) - Read-only. A promise that resolves to the preloaded response, if any. - **clientId** (DOMString) - Read-only. The ID of the client that initiated the fetch. - **resultingClientId** (DOMString) - Read-only. The ID of the resulting client after navigation. - **replacesClientId** (DOMString) - Read-only. The ID of the client being replaced. - **handled** (Promise) - Read-only. A promise that resolves when the event has been handled. ### Methods - **respondWith(r)** - Takes a Promise and uses it as the response to the fetch event. ``` -------------------------------- ### Client.postMessage(message, options) Source: https://www.w3.org/TR/service-workers Sends a message to the client using structured clone options. ```APIDOC ## [POST] Client.postMessage(message, options) ### Description Posts a message to the client with structured clone options. ### Method POST ### Endpoint Client.postMessage(message, options) ### Parameters #### Request Body - **message** (any) - Required - The message to send. - **options** (StructuredSerializeOptions) - Required - Options for structured serialization. ``` -------------------------------- ### Cache.matchAll(request, options) Source: https://www.w3.org/TR/service-workers The `matchAll(request, options)` method returns a Promise that resolves to an array of all matching Responses in the cache. ```APIDOC ## [GET] Cache.matchAll(request, options) ### Description Returns a Promise that resolves to an array of all matching Responses in the cache. ### Method GET ### Endpoint Cache.matchAll(request, options) ### Parameters #### Path Parameters - **request** (RequestInfo) - Optional - The request to match against. If omitted, returns all responses. - **options** (CacheQueryOptions) - Optional - Query options. ### Response #### Success Response (200) - **FrozenArray** - An array of matching responses. #### Response Example ``` FrozenArray ``` ```