# Clients API

> self.clients 暴露的 Clients 接口及其 get()、matchAll()、openWindow()、claim() 成员，抛出 InvalidAccessError 的条件，以及通知点击聚焦窗口的模式。

`Clients` 让 Service Worker 查找它控制或能够控制的文档与 worker、聚焦客户端、打开窗口，还能接管激活前就已加载的页面。接口只在 Service Worker 内提供，用 `self.clients` 访问。它与 Service Worker 同期发布，从 Chrome 40、Edge 17、Firefox 44 和 Safari 11.1 起可用（BCD `api.Clients`）。

## 语法

```js
// 仅在 service worker 内
const client = await self.clients.get(id);
const clients = await self.clients.matchAll(options);
const windowClient = await self.clients.openWindow(url);
await self.clients.claim();
```

四个方法都返回 Promise。`self.clients` 是一个 `Clients` 对象；每个结果是 `Client`（worker 与文档）或 `WindowClient`（文档），后者额外提供 `focused`、`visibilityState`、`focus()` 与 `navigate()`。

## 成员

该接口有四个方法，没有属性。

| 成员 | 返回值 | 行为 |
|---|---|---|
| `get(id)` | `Promise<Client \| undefined>` | 以 `id` 匹配的客户端兑现（id 来自 `FetchEvent.clientId`、`ExtendableMessageEvent.source.id` 或先前的 `matchAll()`），没有匹配时为 `undefined`。 |
| `matchAll(options)` | `Promise<Client[]>` | 所有匹配 `options` 的客户端，最近聚焦的排在前面。`options.type` 可为 `'window'`（默认）、`'worker'`、`'sharedworker'` 或 `'all'`；`options.includeUncontrolled`（默认 `false`）会加入同源但不受本 worker 控制的客户端。 |
| `openWindow(url)` | `Promise<WindowClient \| null>` | 在 `url` 打开一个顶层浏览上下文。`url` 同源时以新窗口的客户端兑现，否则为 `null`。应用源下没有任何窗口具有瞬时激活时，以 `InvalidAccessError` 拒绝。 |
| `claim()` | `Promise<void>` | 让处于 active 状态的 worker 成为 scope 内所有未被其他 worker 控制的客户端的控制者，并在每个页面的 `navigator.serviceWorker` 上触发 `controllerchange`。 |

在 worker 激活之前打开的页面不受它控制；不刷新就接管这些页面，`claim()` 是唯一途径。它与 `skipWaiting()` 搭配会在页面打开状态下更换 worker，因此只有明确需要这种行为时才组合使用。

## 异常

`openWindow()` 在下表所列情形下以 `DOMException`（`InvalidAccessError`）或 `TypeError` 拒绝；规范还规定，导航步骤若抛出异常，则以该异常拒绝。

| 异常与方法 | 条件 |
|---|---|
| `openWindow()` 的 `InvalidAccessError` | 应用源下没有任何窗口具有瞬时激活。Chromium 的报错是 `Not allowed to open a window.`；Chromium 在 Worker 当前不允许窗口交互时（`IsWindowInteractionAllowed()` 检查）拒绝，并在使用时消耗这份许可。`notificationclick` 处理函数通常允许窗口交互，`push` 处理函数不允许。 |
| `openWindow()` 的 `TypeError` | `url` 相对于 worker 地址不是合法 URL，或者是 `about:blank`。 |
| `claim()` 的 `InvalidStateError` | 该 worker 不是注册上处于 active 状态的 worker，例如在 `install` 中调用。 |

:::caution
当应用源下没有任何窗口具有瞬时激活（transient activation）时，`clients.openWindow()` 会以 `InvalidAccessError` DOMException 拒绝，见 [Service Workers 规范](https://w3c.github.io/ServiceWorker/)与 [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Clients/openWindow)。Chromium 的 [service_worker_clients.cc](https://chromium.googlesource.com/chromium/src/+/main/third_party/blink/renderer/modules/service_worker/service_worker_clients.cc) 使用的消息为 "Not allowed to open a window."。应像下面的示例那样直接在 `notificationclick` 处理函数中调用 `openWindow()`，而不要在 `push` 处理函数中或无关的异步操作之后调用。
:::

## 示例

在 Service Worker 内处理通知点击，在页面代码中检测 worker 是否已接管页面。

### 通知点击时聚焦已打开的窗口，否则新开一个

查找已经位于目标路径的客户端并聚焦它，找不到时才调用 `openWindow()`。把工作放在 `waitUntil()` 内，可以让 `openWindow()` 所需的用户激活窗口保持有效。

```js
self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  event.waitUntil((async () => {
    const all = await self.clients.matchAll({ type: 'window', includeUncontrolled: true });
    const existing = all.find((c) => new URL(c.url).pathname === '/chat/');
    if (existing) {
      await existing.focus();
      existing.postMessage({ type: 'open-thread', id: event.notification.data.threadId });
      return;
    }
    const opened = await self.clients.openWindow(`/chat/?thread=${event.notification.data.threadId}`);
    if (opened === null) console.warn('Window opened cross-origin; cannot message it');
  })());
});
```

需要 `includeUncontrolled: true`，因为在上一个 worker 处于 active 状态时从通知打开的标签页，可能还不受本 worker 控制。对 `WindowClient` 调用 `postMessage()`，消息会到达页面 `navigator.serviceWorker` 的 `message` 事件。

### 在页面侧检测控制状态并等待 `claim()`

`claim()` 在 worker 中执行，但效果体现在页面上。首次加载与强制刷新后 `navigator.serviceWorker.controller` 为 `null`；页面只在有控制者后才启用离线 UI，否则按仅在线站点运行。

```js
function enableOfflineUi() {
  document.querySelector("#offline-badge").hidden = false;
}

if (!("serviceWorker" in navigator)) {
  // 完全没有 service worker：仅在线，无需等待。
} else if (navigator.serviceWorker.controller) {
  enableOfflineUi();
} else {
  // 尚未受控：worker 中的 claim() 会在这里触发 controllerchange。
  navigator.serviceWorker.addEventListener("controllerchange", enableOfflineUi, { once: true });
}
```

worker 中若没有 `claim()`，本次加载不会触发 `controllerchange`，标记会一直隐藏到下一次导航；这就是保留默认接管行为所付出的代价。

## 另请参阅

- [Service Workers specification: Clients interface](https://w3c.github.io/ServiceWorker/#clients-interface)（w3c.github.io）
- [Clients: openWindow() method](https://developer.mozilla.org/en-US/docs/Web/API/Clients/openWindow)（developer.mozilla.org）
- [Service worker 生命周期](/zh/reference/service-worker/lifecycle/)
- [Service worker 更新流程与 skipWaiting()](/zh/reference/service-worker/update-skipwaiting/)
- [Web Push](/zh/reference/notifications/web-push/)
- [通知操作与徽标](/zh/reference/notifications/notification-actions-badge/)