NotificationEvent
        
        
          
                Baseline
                
                  Widely available
                
                 *
              
        
        
        
          
                
              
                
              
                
              
        
        
      
      This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2023年3月.
* Some parts of this feature may have varying levels of support.
备注: 此特性仅在 Service Worker 中可用。
Notifications API 的 NotificationEvent 接口表示在 ServiceWorker 的 ServiceWorkerGlobalScope 上触发的通知事件。
该接口继承自 ExtendableEvent 接口。
备注:只有在 ServiceWorkerGlobalScope 对象上触发的持久通知事件才会使用 NotificationEvent 接口。非持久通知事件在 Notification 对象上触发,使用 Event 接口。
构造函数
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> # notificationevent>  | 
            
备注:此接口在 Notifications API 中指定,但是可以通过 ServiceWorkerGlobalScope 访问。
浏览器兼容性
Loading…