|
| 1 | +/* Minimal service worker for DailyNest |
| 2 | + - Provides basic install/activate flows for immediate activation |
| 3 | + - Listens for push and notificationclick events |
| 4 | + - Expand this with caching or push handling as needed |
| 5 | +*/ |
| 6 | + |
| 7 | +self.addEventListener("install", (event) => { |
| 8 | + // Activate immediately |
| 9 | + event.waitUntil(self.skipWaiting()); |
| 10 | +}); |
| 11 | + |
| 12 | +self.addEventListener("activate", (event) => { |
| 13 | + event.waitUntil(self.clients.claim()); |
| 14 | +}); |
| 15 | + |
| 16 | +// Push handler: show notification if payload provided |
| 17 | +self.addEventListener("push", (event) => { |
| 18 | + let data = {}; |
| 19 | + try { |
| 20 | + data = event.data ? event.data.json() : {}; |
| 21 | + } catch (e) { |
| 22 | + data = { |
| 23 | + title: "DailyNest", |
| 24 | + body: event.data ? event.data.text() : "New content available", |
| 25 | + }; |
| 26 | + } |
| 27 | + |
| 28 | + const title = data.title || "DailyNest"; |
| 29 | + const options = { |
| 30 | + body: data.body || "Tap to read the latest article", |
| 31 | + icon: "/favicon.png", |
| 32 | + badge: "/favicon.png", |
| 33 | + data: data.url || "/", |
| 34 | + }; |
| 35 | + |
| 36 | + event.waitUntil(self.registration.showNotification(title, options)); |
| 37 | +}); |
| 38 | + |
| 39 | +self.addEventListener("notificationclick", (event) => { |
| 40 | + event.notification.close(); |
| 41 | + const url = event.notification.data || "/"; |
| 42 | + event.waitUntil( |
| 43 | + self.clients |
| 44 | + .matchAll({ type: "window", includeUncontrolled: true }) |
| 45 | + .then((clients) => { |
| 46 | + for (const client of clients) { |
| 47 | + if (client.url === url && "focus" in client) return client.focus(); |
| 48 | + } |
| 49 | + if (self.clients.openWindow) return self.clients.openWindow(url); |
| 50 | + }), |
| 51 | + ); |
| 52 | +}); |
0 commit comments