From c35c20faeb58e42a7ddcc84da68df453e71b79d4 Mon Sep 17 00:00:00 2001 From: Kevin Riehl Date: Wed, 11 Mar 2026 20:46:49 -0700 Subject: [PATCH] Add service worker for push notifications --- public/sw.js | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 public/sw.js diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 0000000..365399b --- /dev/null +++ b/public/sw.js @@ -0,0 +1,41 @@ +/* eslint-disable no-restricted-globals */ + +self.addEventListener('push', (event) => { + if (!event.data) return; + + try { + const payload = event.data.json(); + const options = { + body: payload.body, + icon: payload.icon || '/favicon.ico', + badge: '/favicon.ico', + data: { url: payload.url || '/' }, + }; + + event.waitUntil(self.registration.showNotification(payload.title, options)); + } catch { + // Silently fail + } +}); + +self.addEventListener('notificationclick', (event) => { + event.notification.close(); + + const url = event.notification.data?.url || '/'; + + event.waitUntil( + self.clients + .matchAll({ type: 'window', includeUncontrolled: true }) + .then((clientList) => { + // Focus existing window if available + for (const client of clientList) { + if (client.url.includes(self.location.origin)) { + client.navigate(url); + return client.focus(); + } + } + // Otherwise open new window + return self.clients.openWindow(url); + }), + ); +});