NotificationEvent:notification 属性

可用性有限

此特性不是基线特性,因为它在一些最广泛使用的浏览器中不起作用。

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

NotificationEvent 接口的notification 只读属性返回在触发事件时被点击的 Notification 实例。该 Notification 提供了对许多属性的只读访问,这些属性是在 Notification 实例化时设置的,例如 tagdata 属性,允许你在 notificationclick 事件中存储信息以供后续使用。

一个 Notification 对象。

示例

js
self.addEventListener("notificationclick", (event) => {
  console.log("On notification click");

  // Data can be attached to the notification so that you
  // can process it in the notificationclick handler.
  console.log(`Notification Tag: ${event.notification.tag}`);
  console.log(`Notification Data: ${event.notification.data}`);
  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
# dom-notificationevent-notification

浏览器兼容性