--- title: Clients slug: Web/API/Clients tags: - API - Clients - Experimental - Interface - NeedsTranslation - Reference - Service Workers - Service worker API - ServiceWorker - TopicStub - Workers translation_of: Web/API/Clients ---
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
The Clients
interface provides access to {{domxref("Client")}} objects. Access it via {{domxref("ServiceWorkerGlobalScope", "self")}}.clients
within a service worker.
The following example shows an existing chat window or creates a new one when the user clicks a notification.
addEventListener('notificationclick', event => { event.waitUntil(async function() { const allClients = await clients.matchAll({ includeUncontrolled: true }); let chatClient; // Let's see if we already have a chat window open: for (const client of allClients) { const url = new URL(client.url); if (url.pathname == '/chat/') { // Excellent, let's use it! client.focus(); chatClient = client; break; } } // If we didn't find an existing chat window, // open a new one: if (!chatClient) { chatClient = await clients.openWindow('/chat/'); } // Message the client: chatClient.postMessage("New chat messages!"); }()); });
Specification | Status | Comment |
---|---|---|
{{SpecName('Service Workers', '#clients', 'Clients')}} | {{Spec2('Service Workers')}} | Initial definition |
{{Compat("api.Clients")}}