WindowClient

Baseline 广泛可用 *

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

* 此特性的某些部分可能存在不同级别的支持。

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

WindowClient 接口是 ServiceWorker API 的一部分,它表示一个由活动工作线程控制的、属于浏览上下文中的文档的 Service Worker 客户端范围。Service Worker 客户端独立地为自身的加载和子资源选择并使用一个 Service Worker。

Client WindowClient

实例方法

WindowClient 从其父接口 Client 继承了方法。

WindowClient.focus()

将用户输入焦点给予当前客户端。

WindowClient.navigate()

将指定的 URL 加载到受控的客户端页面中。

实例属性

WindowClient 从其父接口 Client 继承了属性。

WindowClient.ancestorOrigins 只读 实验性

一个字符串数组,表示此 WindowClient 所代表的浏览上下文的祖先源,顺序相反。

WindowClient.focused 只读

一个布尔值,指示当前客户端是否具有焦点。

WindowClient.visibilityState 只读

指示当前客户端的可见性。此值可以是 "hidden""visible" 之一。

示例

js
self.addEventListener("notificationclick", (event) => {
  console.log("On notification click: ", event.notification.tag);
  event.notification.close();

  // This looks to see if the current is already open and
  // focuses if it is
  event.waitUntil(
    clients
      .matchAll({
        type: "window",
      })
      .then((clientList) => {
        for (const client of clientList) {
          if (client.url === "/" && "focus" in client) {
            client.focus();
            break;
          }
        }
        if (clients.openWindow) return clients.openWindow("/");
      }),
  );
});

规范

规范
Service Workers
# windowclient

浏览器兼容性

另见