Clients

Baseline 已广泛支持

此功能已成熟,可跨多种设备和浏览器版本工作。它自 ⁨2018 年 4 月⁩ 起已在所有浏览器中可用。

注意:此功能仅在 Service Workers 中可用。

Clients 接口提供了对 Client 对象的访问。在 service worker 中,通过 self.clients 访问它。

实例方法

Clients.get()

返回一个 Promise,该 Promise 解析为一个与给定 id 匹配的 Client

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

浏览器兼容性

另见