--- title: Clients slug: Web/API/Clients translation_of: Web/API/Clients ---
{{SeeCompatTable}}{{APIRef("Service Workers API")}}
Clients
接口提供对 {{domxref("Client")}} 对象的访问. 通过在 service worker 中使用 {{domxref("ServiceWorkerGlobalScope", "self")}}.clients
访问它.
下面示例显示一个已有的聊天窗口,或者当用户点击通知时创建新的窗口.
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")}}