WindowClient: focus() 方法

Baseline 已廣泛支援

此功能已成熟,可跨多種裝置和瀏覽器版本工作。它自 ⁨2018 年 4 月⁩ 起已在所有瀏覽器中可用。

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

WindowClient 介面的 focus() 方法將使用者輸入焦點賦予當前客戶端,並返回一個 Promise,該 Promise 解析為現有的 WindowClient

語法

js
focus()

引數

無。

返回值

一個 Promise,解析為現有的 WindowClient

異常

InvalidAccessError DOMException

如果應用程式源中的任何視窗都沒有瞬時啟用,則 Promise 將被此異常拒絕。

安全要求

  • 應用程式源中至少有一個視窗必須具有瞬時啟用

示例

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) return client.focus();
        }
        if (clients.openWindow) return clients.openWindow("/");
      }),
  );
});

規範

規範
Service Workers
# client-focus

瀏覽器相容性