ServiceWorkerGlobalScope: notificationclick 事件
注意:此功能僅在 Service Workers 中可用。
notificationclick 事件是 ServiceWorkerGlobalScope 介面的一個事件,當透過 ServiceWorkerRegistration.showNotification() 觸發的系統通知被點選時,會觸發該事件。
在主執行緒或非 Service Worker 的 worker 中使用 Notification() 建構函式建立的通知,將在 Notification 物件本身上收到一個 click 事件。
此事件不可取消,也不會冒泡。
語法
在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。
js
addEventListener("notificationclick", (event) => { })
onnotificationclick = (event) => { }
事件型別
這是一個 NotificationEvent。繼承自 ExtendableEvent 和 Event。
事件屬性
繼承自其祖先 ExtendableEvent 和 Event 的屬性。.
NotificationEvent.notification只讀-
返回一個
Notification物件,表示被點選以觸發事件的通知。 NotificationEvent.action只讀-
返回使用者點選的通知按鈕的字串 ID。如果使用者點選了通知中的操作按鈕以外的區域,或者通知沒有按鈕,則此值為空字串。
示例
您可以在 addEventListener 方法中使用 notificationclick 事件。
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("/");
}),
);
});
或者使用 onnotificationclick 事件處理程式屬性。
js
self.onnotificationclick = (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("/");
}),
);
};
您可以在 notificationclick 事件處理程式中使用 event.action 來處理事件操作。
js
navigator.serviceWorker.register("sw.js");
Notification.requestPermission().then((result) => {
if (result === "granted") {
navigator.serviceWorker.ready.then((registration) => {
// Show a notification that includes an action titled Archive.
registration.showNotification("New mail from Alice", {
actions: [
{
action: "archive",
title: "Archive",
},
],
});
});
}
});
self.addEventListener("notificationclick", (event) => {
event.notification.close();
if (event.action === "archive") {
// User selected the Archive action.
archiveEmail();
} else {
// User selected (e.g., clicked in) the main body of notification.
clients.openWindow("/inbox");
}
});
規範
| 規範 |
|---|
| Notifications API # 啟用通知 |
| Notifications API # dom-serviceworkerglobalscope-onnotificationclick |
瀏覽器相容性
載入中…