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

瀏覽器相容性

另見