NotificationEvent

Baseline 廣泛可用 *

此功能已成熟,並可在許多裝置和瀏覽器版本上執行。自 2023 年 3 月以來,它已在各種瀏覽器中可用。

* 此特性的某些部分可能存在不同級別的支援。

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

NotificationEvent 介面是 Notifications API 的一部分,它代表了在 ServiceWorkerServiceWorkerGlobalScope 上觸發的一個通知事件。

此介面繼承自 ExtendableEvent 介面。

注意: 只有在 ServiceWorkerGlobalScope 物件上觸發的永續性通知事件才會實現 NotificationEvent 介面。在 Notification 物件上觸發的非永續性通知事件則實現 Event 介面。

Event ExtendableEvent NotificationEvent

建構函式

NotificationEvent()

建立一個新的 NotificationEvent 物件。

例項屬性

同時也繼承了其父介面 ExtendableEvent 的屬性。.

NotificationEvent.notification 只讀

返回一個 Notification 物件,表示被點選以觸發事件的通知。

NotificationEvent.action 只讀

返回使用者點選的通知按鈕的字串 ID。如果使用者點選了通知中的操作按鈕以外的區域,或者通知沒有按鈕,則此值為空字串。

例項方法

同時也繼承了其父介面 ExtendableEvent 的方法。.

示例

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

規範

規範
Notifications API
# notificationevent

注意: 該介面在 Notifications API 中定義,但透過 ServiceWorkerGlobalScope 訪問。

瀏覽器相容性