From b62c6052c8f6380b9c89aabd6f6bad1b002322f2 Mon Sep 17 00:00:00 2001 From: Blueray <83096078+blueraymusic@users.noreply.github.com> Date: Mon, 21 Jul 2025 16:18:08 -0500 Subject: [PATCH] Update service-worker.js Changes: - Optional chaining to avoid runtime errors - for...of for readability - Defensive checks for event.data and event.notification.data Signed-off-by: Blueray <83096078+blueraymusic@users.noreply.github.com> --- app/views/pwa/service-worker.js | 45 +++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/app/views/pwa/service-worker.js b/app/views/pwa/service-worker.js index 68d5c2ee..42acf427 100644 --- a/app/views/pwa/service-worker.js +++ b/app/views/pwa/service-worker.js @@ -24,3 +24,48 @@ // }) // ) // }) + + +// _____--------_____ +// Improve + +self.addEventListener("push", async (event) => { + if (!event.data) return + + try { + const { title, options } = await event.data.json() + if (!title || !options) return + + event.waitUntil( + self.registration.showNotification(title, options) + ) + } catch (error) { + console.error(" Failed to Parse the Json:", error) + } +}) + + +self.addEventListener("notificationclick", (event) => { + event.notification.close() + + const targetPath = event.notification?.data?.path + if (!targetPath) return + + event.waitUntil( + clients.matchAll({ type: "window", includeUncontrolled: true }).then((clientList) => { + for (const client of clientList) { + const clientPath = new URL(client.url).pathname + + if (clientPath === targetPath && "focus" in client) { + return client.focus() + } + } + + // No matching tab found, open new one + if (clients.openWindow) { + return clients.openWindow(targetPath) + } + }) + ) +}) +