Clients
注意:此功能仅在 Service Workers 中可用。
Clients 接口提供了对 Client 对象的访问。在 service worker 中,通过 访问它。self.clients
实例方法
Clients.get()Clients.matchAll()-
返回一个
Promise,该 Promise 解析为一个Client对象数组。一个选项参数允许你控制返回的客户端类型。 Clients.openWindow()-
为给定的 URL 打开一个新的浏览器窗口,并返回一个
Promise,该 Promise 解析为新的WindowClient。 Clients.claim()-
允许一个活动的 service worker 将自身设置为其
scope内所有客户端的controller。
示例
以下示例展示了当用户点击通知时,显示现有聊天窗口或创建一个新窗口。
js
addEventListener("notificationclick", (event) => {
event.waitUntil(
(async () => {
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:
chatClient ??= await clients.openWindow("/chat/");
// Message the client:
chatClient.postMessage("New chat messages!");
})(),
);
});
规范
| 规范 |
|---|
| Service Workers # clients-interface |
浏览器兼容性
加载中…