Clients

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2018.

实验性: 这是一项实验性技术
在将其用于生产之前,请仔细检查浏览器兼容性表格

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

方法

Clients.get()

返回一个匹配给定 idClientPromise .

Clients.matchAll()

返回一个 Client 对象数组的 Promise . options 参数允许你控制返回的 clients 类型。

Clients.openWindow()

打开给定 URL 的新浏览器窗口,并返回新 WindowClient a 的 Promise .

Clients.claim()

允许一个激活的 service worker 将自己设置为其scope 内所有 clients 的 controller .

示例

下面示例显示一个已有的聊天窗口,或者当用户点击通知时创建新的窗口。

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!");
    })(),
  );
});

规范

Specification
Service Workers
# clients-interface

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Clients
claim
get
matchAll
options.includeUncontrolled parameter
openWindow

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
Partial support
Partial support
No support
No support
See implementation notes.
Has more compatibility info.

See also