Clients: openWindow() 方法

Baseline 已廣泛支援

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

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

Clients 介面的 openWindow() 方法會建立一個新的頂級瀏覽上下文並載入指定的 URL。如果呼叫指令碼沒有顯示彈出視窗的許可權,openWindow() 將會丟擲 InvalidAccessError 異常。

在 Firefox 中,只有在作為通知點選事件的結果呼叫時,才允許使用此方法顯示彈出視窗。

在 Android 版 Chrome 中,該方法可能會在使用者主螢幕上已新增的獨立 Web 應用提供的現有瀏覽上下文中開啟 URL。最近,這也適用於 Windows 版 Chrome。

語法

js
openWindow(url)

引數

url

一個字串,代表您想在視窗中開啟的客戶端的 URL。通常,此值必須與呼叫指令碼同源。

返回值

一個 Promise,如果 URL 與 Service Worker 同源,則解析為 WindowClient 物件;否則解析為 null 值。

異常

InvalidAccessError DOMException

如果應用程式源中的所有視窗都沒有 瞬時啟用,則 Promise 將會因該異常而被拒絕。

安全要求

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

示例

js
// Send notification to OS if applicable
if (self.Notification.permission === "granted") {
  const notificationObject = {
    body: "Click here to view your messages.",
    data: { url: `${self.location.origin}/some/path` },
    // data: { url: 'http://example.com' },
  };
  self.registration.showNotification(
    "You've got messages!",
    notificationObject,
  );
}

// Notification click event listener
self.addEventListener("notificationclick", (e) => {
  // Close the notification popout
  e.notification.close();
  // Get all the Window clients
  e.waitUntil(
    clients.matchAll({ type: "window" }).then((clientsArr) => {
      const windowToFocus = clientsArr.find(
        (windowClient) => windowClient.url === e.notification.data.url,
      );
      if (windowToFocus) {
        // If a Window tab matching the targeted URL already exists, focus that;
        windowToFocus.focus();
      } else {
        // Otherwise, open a new tab to the applicable URL and focus it.
        clients
          .openWindow(e.notification.data.url)
          .then((windowClient) => (windowClient ? windowClient.focus() : null));
      }
    }),
  );
});

規範

規範
Service Workers
# clients-openwindow

瀏覽器相容性