Clients
Experimental: 这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。
Clients
接口提供对 Client
对象的访问。通过在 service worker (en-US) 中使用
访问它。self
.clients
方法
Clients.get()
Clients.matchAll()
Clients.openWindow()
-
打开给定 URL 的新浏览器窗口,并返回新
WindowClient
a 的Promise
. Clients.claim()
-
允许一个激活的 service worker 将自己设置为其
scope
(en-US) 内所有 clients 的controller
.
示例
下面示例显示一个已有的聊天窗口,或者当用户点击通知时创建新的窗口。
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 |
---|
Service Workers # clients-interface |
浏览器兼容性
BCD tables only load in the browser