feat(templates/components): add push notification handling to service worker
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
This commit is contained in:
1 file changed
+41
-3
@@ -1,4 +1,5 @@
|
||||
// Empty Service Worker
|
||||
const CACHE = "v1";
|
||||
|
||||
self.addEventListener("install", (event) => {
|
||||
self.skipWaiting();
|
||||
});
|
||||
@@ -7,6 +8,43 @@ self.addEventListener("activate", (event) => {
|
||||
event.waitUntil(self.clients.claim());
|
||||
});
|
||||
|
||||
self.addEventListener("fetch", (event) => {
|
||||
// Do nothing
|
||||
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);
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user