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); + }), + ); + } });