ServiceWorkerGlobalScope: notificationclick イベント
利用可能性は限定的
この機能はベースラインではありません。最も広く使用されているブラウザーの一部で動作しません。
もっと多くのブラウザーがこの機能に対応してほしいですか? 理由を教えてください。
安全なコンテキスト用: この機能は一部またはすべての対応しているブラウザーにおいて、安全なコンテキスト (HTTPS) でのみ利用できます。
メモ: この機能はサービスワーカー内でのみ利用可能です。
notificationclick は ServiceWorkerGlobalScope インターフェイスのイベントで、ServiceWorkerRegistration.showNotification() によって生成されたシステム通知がクリックされたことを示すために発生します。
メインスレッドまたはサービスワーカー以外のワーカーで Notification() コンストラクターを使って作成された通知では、代わりに click イベントが Notification オブジェクト自体に発生します。
このイベントはキャンセル不可で、バブリングしません。
構文
イベント名は addEventListener() で使用してください。
addEventListener("notificationclick", (event) => { })
または、このインターフェイスのイベントハンドラープロパティにイベントハンドラーを代入します。
onnotificationclick = (event) => { }
イベント型
NotificationEvent です。ExtendableEvent および Event を継承しています。
例
notificationclick イベント名は addEventListener() で使用してください。
self.addEventListener("notificationclick", (event) => {
console.log("On notification click: ", event.notification.tag);
event.notification.close();
// 対象のウィンドウが開いているか確認し、
// 開いていればフォーカス
event.waitUntil(
clients
.matchAll({
type: "window",
})
.then((clientList) => {
for (const client of clientList) {
if (
client.url === new URL("/", self.location.origin).href &&
"focus" in client
) {
return client.focus();
}
}
if (clients.openWindow) return clients.openWindow("/");
}),
);
});
または、onnotificationclick イベントハンドラープロパティを使用します。ただし、onnotificationclick で追加された他のイベントリスナーがある場合、このプロパティによって置き換えられます。
self.onnotificationclick = (event) => {
console.log("On notification click: ", event.notification.tag);
event.notification.close();
// 対象のウィンドウが開いているか確認し、
// 開いていればフォーカス
event.waitUntil(
clients
.matchAll({
type: "window",
})
.then((clientList) => {
for (const client of clientList) {
if (
client.url === new URL("/", self.location.origin).href &&
"focus" in client
) {
return client.focus();
}
}
if (clients.openWindow) return clients.openWindow("/");
}),
);
};
notificationclick イベントハンドラー内で event.action を使って、イベントのアクションを処理できます。
navigator.serviceWorker.register("sw.js");
Notification.requestPermission().then((result) => {
if (result === "granted") {
navigator.serviceWorker.ready.then((registration) => {
// "Archive" をタイトルとするアクション付き通知を表示
registration.showNotification("New mail from Alice", {
actions: [
{
action: "archive",
title: "Archive",
},
],
});
});
}
});
self.addEventListener("notificationclick", (event) => {
event.notification.close();
if (event.action === "archive") {
// ユーザーが "Archive" アクションを選択
archiveEmail();
} else {
// ユーザーが通知本文を選択(例:クリック)
clients.openWindow("/inbox");
}
});
仕様書
| 仕様書 |
|---|
| Notifications API> # activating-a-notification> |
| Notifications API> # dom-serviceworkerglobalscope-onnotificationclick> |