blob: 713e7536210a96c69a6ba310f98c524b66fb3067 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
---
title: Clients
slug: Web/API/Clients
translation_of: Web/API/Clients
---
<p>{{SeeCompatTable}}{{APIRef("Service Workers API")}}</p>
<p><span class="seoSummary"><code>Clients</code> 接口提供对 {{domxref("Client")}} 对象的访问. 通过在 <a href="/en-US/docs/Web/API/ServiceWorker_API">service worker</a> 中使用 <code>{{domxref("ServiceWorkerGlobalScope", "self")}}.clients</code> 访问它.</span></p>
<h2 id="方法">方法</h2>
<dl>
<dt>{{domxref("Clients.get()")}}</dt>
<dd>返回一个匹配给定 {{domxref("Client.id", "id")}} 的 {{domxref("Client")}} 的 {{jsxref("Promise")}} .</dd>
<dt>{{domxref("Clients.matchAll()")}}</dt>
<dd>返回一个 {{domxref("Client")}} 对象数组的 {{jsxref("Promise")}} . options参数允许您控制返回的clients类型. </dd>
<dt>{{domxref("Clients.openWindow()")}}</dt>
<dd>打开给定URL的新浏览器窗口,并返回新 {{domxref("WindowClient")}} a 的 {{jsxref("Promise")}} .</dd>
<dt>{{domxref("Clients.claim()")}}</dt>
<dd>允许一个激活的 service worker 将自己设置为其{{domxref("ServiceWorkerRegistration.scope", "scope")}} 内所有 clients 的 {{domxref("ServiceWorkerContainer.controller", "controller")}} . </dd>
</dl>
<h2 id="示例">示例</h2>
<p>下面示例显示一个已有的聊天窗口,或者当用户点击通知时创建新的窗口.</p>
<pre class="brush: js">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!");
}());
});
</pre>
<h2 id="规范">规范</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td>{{SpecName('Service Workers', '#clients', 'Clients')}}</td>
<td>{{Spec2('Service Workers')}}</td>
<td>Initial definition</td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<div>
<p>{{Compat("api.Clients")}}</p>
</div>
<h2 id="See_also">See also</h2>
<ul>
<li><a href="/en-US/docs/Web/API/ServiceWorker_API/Using_Service_Workers">Using Service Workers</a></li>
<li><a href="https://jakearchibald.github.io/isserviceworkerready/">Is ServiceWorker ready?</a></li>
<li>{{jsxref("Promise")}}</li>
</ul>
|