49 lines
1.5 KiB
JavaScript
49 lines
1.5 KiB
JavaScript
/* Prabhupāda Says — Web Push service worker.
|
|
*
|
|
* Handles incoming push messages (shows a notification) and clicks (focuses
|
|
* an existing tab or opens the target URL). The push payload is the JSON the
|
|
* BFF sends: { title, body, url, icon, tag }.
|
|
*/
|
|
|
|
self.addEventListener("install", () => self.skipWaiting());
|
|
self.addEventListener("activate", (event) =>
|
|
event.waitUntil(self.clients.claim()),
|
|
);
|
|
|
|
self.addEventListener("push", (event) => {
|
|
let data = {};
|
|
try {
|
|
data = event.data ? event.data.json() : {};
|
|
} catch {
|
|
data = { body: event.data && event.data.text ? event.data.text() : "" };
|
|
}
|
|
const title = data.title || "Prabhupāda Says";
|
|
const options = {
|
|
body: data.body || "",
|
|
icon: data.icon || "/logo_dark.png",
|
|
badge: "/logo_dark.png",
|
|
tag: data.tag || undefined,
|
|
data: { url: data.url || "/" },
|
|
};
|
|
event.waitUntil(self.registration.showNotification(title, options));
|
|
});
|
|
|
|
self.addEventListener("notificationclick", (event) => {
|
|
event.notification.close();
|
|
const url =
|
|
(event.notification.data && event.notification.data.url) || "/";
|
|
event.waitUntil(
|
|
self.clients
|
|
.matchAll({ type: "window", includeUncontrolled: true })
|
|
.then((list) => {
|
|
for (const client of list) {
|
|
if ("focus" in client) {
|
|
if ("navigate" in client) client.navigate(url);
|
|
return client.focus();
|
|
}
|
|
}
|
|
if (self.clients.openWindow) return self.clients.openWindow(url);
|
|
}),
|
|
);
|
|
});
|