API in Service Worker
Clients API
Published
Clients lets a service worker find the documents and workers it controls or could control,
focus them, open windows, and take control of pages loaded before activation. It is available
only inside a service worker as self.clients. The interface shipped with service workers
in Chrome 40, Edge 17, Firefox 44, and Safari 11.1 (BCD api.Clients).
Syntax
Section titled “Syntax”// Inside the service worker onlyconst client = await self.clients.get(id);const clients = await self.clients.matchAll(options);const windowClient = await self.clients.openWindow(url);await self.clients.claim();All four methods return promises. self.clients is a Clients object; each result is a Client (for workers and documents) or a WindowClient (documents), which adds focused, visibilityState, focus(), and navigate().
Members
Section titled “Members”The interface has four methods and no attributes.
| Member | Returns | Behaviour |
|---|---|---|
get(id) |
Promise<Client | undefined> |
Resolves with the client whose id matches (ids come from FetchEvent.clientId, ExtendableMessageEvent.source.id, or an earlier matchAll()), or undefined when none does. |
matchAll(options) |
Promise<Client[]> |
All clients matching options, most recently focused first. options.type is 'window' (default), 'worker', 'sharedworker', or 'all'; options.includeUncontrolled (default false) adds same-origin clients not controlled by this worker. |
openWindow(url) |
Promise<WindowClient | null> |
Opens a top-level browsing context at url. Resolves with the new client when the URL is same-origin and with null otherwise. Rejects with InvalidAccessError when no window in the app’s origin has transient activation. |
claim() |
Promise<void> |
Makes the active worker the controller of every in-scope client that is not controlled by another worker, firing controllerchange on each page’s navigator.serviceWorker. |
Pages opened before the worker activated are not controlled by it; claim() is the only way to take them over without a reload. Combined with skipWaiting() it swaps the worker under an open page, so use the pair only when you explicitly want that behaviour.
Exceptions
Section titled “Exceptions”openWindow() rejects with a DOMException (InvalidAccessError) or a TypeError in the cases listed below; the specification also rejects with the exception when the navigation step throws.
| Exception and method | Condition |
|---|---|
InvalidAccessError from openWindow() |
no window in the app’s origin has transient activation. Chromium’s message is Not allowed to open a window.; Chromium rejects when the worker’s window interaction is not currently allowed (the IsWindowInteractionAllowed() check) and consumes that allowance on use. A notificationclick handler is where it is normally allowed; a push handler is not. |
TypeError from openWindow() |
url is not a valid URL relative to the worker’s location, or it is about:blank. |
InvalidStateError from claim() |
the worker is not the registration’s active worker, for example when called in install. |
Examples
Section titled “Examples”Handle notification clicks in the service worker and detect whether it controls the page from page code.
Focusing an open window or opening one on notification click
Section titled “Focusing an open window or opening one on notification click”Look for a client already at the target path and focus it. Call openWindow() only when none exists. Doing the work inside waitUntil() keeps the user-activation window open for openWindow().
self.addEventListener('notificationclick', (event) => { event.notification.close(); event.waitUntil((async () => { const all = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); const existing = all.find((c) => new URL(c.url).pathname === '/chat/'); if (existing) { await existing.focus(); existing.postMessage({ type: 'open-thread', id: event.notification.data.threadId }); return; } const opened = await self.clients.openWindow(`/chat/?thread=${event.notification.data.threadId}`); if (opened === null) console.warn('Window opened cross-origin; cannot message it'); })());});includeUncontrolled: true is needed because a tab opened from a notification while the previous worker was active may not be controlled by this one yet. postMessage() on a WindowClient arrives at the page’s navigator.serviceWorker message event.
Detecting control on the page and waiting for claim()
Section titled “Detecting control on the page and waiting for claim()”claim() runs in the worker, but the page is where its effect matters. navigator.serviceWorker.controller is null on the first load and after a hard reload; the page below enables its offline UI only once a controller exists, and otherwise behaves as an online-only site.
function enableOfflineUi() { document.querySelector("#offline-badge").hidden = false;}
if (!("serviceWorker" in navigator)) { // No service workers at all: online-only, nothing to wait for.} else if (navigator.serviceWorker.controller) { enableOfflineUi();} else { // Not controlled yet: claim() in the worker fires controllerchange here. navigator.serviceWorker.addEventListener("controllerchange", enableOfflineUi, { once: true });}Without claim() in the worker, controllerchange does not fire for this load and the badge stays hidden until the next navigation; that is the trade-off of leaving the default takeover behaviour in place.
See also
Section titled “See also”- Service Workers specification: Clients interface (w3c.github.io)
- Clients: openWindow() method (developer.mozilla.org)
- Service worker lifecycle
- Service worker update flow and skipWaiting()
- Web Push
- Notification actions and badges
Specifications
| Specification | Status |
|---|---|
| None. | |