NotificationEvent

Notifications APINotificationEvent 接口表示在 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(`通知被点击:${event.notification.tag}`);
  event.notification.close();

  // 这会检查当前标签页是否已打开并聚焦
  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("/");
      }),
  );
});

规范

Specification
Notifications API Standard
# notificationevent

备注: 此接口在 Notifications API 中指定,但是可以通过 ServiceWorkerGlobalScope 访问。

浏览器兼容性

BCD tables only load in the browser