Web Notificationsservice
Notifications API 的 NotificationEvent 接口表示在 ServiceWorker 的 ServiceWorkerGlobalScope 上触发的通知事件。
该接口继承自 ExtendableEvent 接口。
[!NOTE] 只有在 ServiceWorkerGlobalScope 对象上触发的持久通知事件才会使用
NotificationEvent接口。非持久通知事件在 Notification 对象上触发,使用Event接口。
构造函数
- NotificationEvent.NotificationEvent
- : 创建一个新的
NotificationEvent对象。
- : 创建一个新的
实例属性
还从其父接口 ExtendableEvent 继承属性。
- NotificationEvent.notification
- : 返回一个 Notification 对象,表示单击以触发事件的通知。
- NotificationEvent.action
- : 返回用户单击的通知按钮的字符串 ID。如果用户单击操作按钮以外的通知,或者通知没有按钮,则此值返回空字符串。
实例方法
还从其父接口 ExtendableEvent 继承方法。
示例
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("/");
}),
);
});
规范
[!NOTE] 此接口在 Notifications API 中指定,但是可以通过 ServiceWorkerGlobalScope 访问。
浏览器兼容性
来源:MDN Web Docs / Mozilla 贡献者 · 作者与贡献记录 · CC BY-SA 2.5。离线整理了版式、链接和媒体显示。
