Add support for receiving push notifications, parsing JSON payload, displaying notifications with title, body, icon, badge and handling click actions to focus or open the associated URL, improving user experience with timely interactive alerts
51 lines
1.1 KiB
JavaScript
51 lines
1.1 KiB
JavaScript
const CACHE = "v1";
|
|
|
|
self.addEventListener("install", (event) => {
|
|
self.skipWaiting();
|
|
});
|
|
|
|
self.addEventListener("activate", (event) => {
|
|
event.waitUntil(self.clients.claim());
|
|
});
|
|
|
|
self.addEventListener("fetch", () => {});
|
|
|
|
self.addEventListener("push", (event) => {
|
|
if (!event.data) return;
|
|
|
|
let data;
|
|
try {
|
|
data = event.data.json();
|
|
} catch {
|
|
return;
|
|
}
|
|
|
|
const title = data.title || "Notification";
|
|
const options = {
|
|
body: data.body || "",
|
|
icon: data.icon || undefined,
|
|
badge: data.badge || undefined,
|
|
data: data.data || {},
|
|
};
|
|
|
|
event.waitUntil(self.registration.showNotification(title, options));
|
|
});
|
|
|
|
self.addEventListener("notificationclick", (event) => {
|
|
event.notification.close();
|
|
|
|
const url = event.notification.data?.url;
|
|
if (url) {
|
|
event.waitUntil(
|
|
self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((clients) => {
|
|
for (const client of clients) {
|
|
if (client.url === url && "focus" in client) {
|
|
return client.focus();
|
|
}
|
|
}
|
|
return self.clients.openWindow(url);
|
|
}),
|
|
);
|
|
}
|
|
});
|