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 访问。

浏览器兼容性