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 bên trong một service worker.self.clients
Phương thức thực thể
Clients.get()Clients.matchAll()-
Trả về một
Promisecho một mảng các đối tượngClient. Đố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
PromisechoWindowClientmới. Clients.claim()-
Cho phép một service worker đang hoạt động tự đặt mình làm
controllercho mọi client trongscopecủ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.
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> |