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.

Note: This feature is only available in Service Workers.

Giao diện Clients cung cấp quyền truy cập vào các đối tượng Client. Hãy truy cập nó thông qua self.clients bên trong một service worker.

Phương thức thực thể

Clients.get()

Trả về một Promise cho một Client khớp với id đã cho.

Clients.matchAll()

Trả về một Promise cho một mảng các đối tượng Client. Đối số tùy chọn cho phép bạn kiểm soát loại client nào được trả về.

Clients.openWindow()

Mở một cửa sổ trình duyệt mới cho URL đã cho và trả về một Promise cho WindowClient mới.

Clients.claim()

Cho phép một service worker đang hoạt động tự đặt mình làm controller cho mọi client trong scope của nó.

Ví dụ

Ví dụ sau hiển thị cách dùng một cửa sổ chat hiện có hoặc tạo cửa sổ mới khi người dùng nhấp vào thông báo.

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

Thông số kỹ thuật

Specification
Service Workers Nightly
# clients-interface

Tương thích trình duyệt

Xem thêm