From 3ed5083551e472bec22d55da4a026757681815cc Mon Sep 17 00:00:00 2001 From: S4NKALP Date: Tue, 30 Jun 2026 10:22:39 +0545 Subject: [PATCH] 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 --- templates/components/sw.js | 44 +++++++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/templates/components/sw.js b/templates/components/sw.js index 5454399..7c60fb9 100644 --- a/templates/components/sw.js +++ b/templates/components/sw.js @@ -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); + }), + ); + } });