Clients - Web APIs 编辑
The Clients
interface provides access to Client
objects. Access it via
within a service worker.self
.clients
Methods
Clients.get()
- Returns a
Promise
for aClient
matching a givenid
. Clients.matchAll()
- Returns a
Promise
for an array ofClient
objects. An options argument allows you to control the types of clients returned. Clients.openWindow()
- Opens a new browser window for a given url and returns a
Promise
for the newWindowClient
. Clients.claim()
- Allows an active service worker to set itself as the
controller
for all clients within itsscope
.
Examples
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!");
}());
});
Specifications
Specification | Status | Comment |
---|---|---|
Service Workers The definition of 'Clients' in that specification. | Working Draft | Initial definition |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论