42 lines
1.6 KiB
JavaScript
42 lines
1.6 KiB
JavaScript
// Peppa service worker (PEP-55): shows Web Push notifications and opens the right page
|
|
// on click. Payload (core/webpush.ts PushPayload): { title, body, url, tag?, sound?, count? }.
|
|
self.addEventListener("install", () => self.skipWaiting());
|
|
self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim()));
|
|
|
|
self.addEventListener("push", (event) => {
|
|
let p = {};
|
|
try {
|
|
p = event.data ? event.data.json() : {};
|
|
} catch {
|
|
p = { title: "Peppa FACTORY", body: event.data ? event.data.text() : "" };
|
|
}
|
|
const shown = self.registration.showNotification(p.title || "Peppa FACTORY", {
|
|
body: p.body || "",
|
|
tag: p.tag,
|
|
renotify: Boolean(p.tag),
|
|
silent: p.sound === false,
|
|
icon: "/icon.svg",
|
|
badge: "/icon.svg",
|
|
data: { url: p.url || "/" },
|
|
});
|
|
const badge = typeof p.count === "number" && self.navigator.setAppBadge ? self.navigator.setAppBadge(p.count).catch(() => {}) : Promise.resolve();
|
|
event.waitUntil(Promise.all([shown, badge]));
|
|
});
|
|
|
|
self.addEventListener("notificationclick", (event) => {
|
|
event.notification.close();
|
|
const url = new URL((event.notification.data && event.notification.data.url) || "/", self.location.origin).href;
|
|
event.waitUntil(
|
|
(async () => {
|
|
const tabs = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
|
|
const same = tabs.find((c) => c.url === url) || tabs.find((c) => new URL(c.url).origin === self.location.origin);
|
|
if (same) {
|
|
await same.focus();
|
|
if (same.url !== url && "navigate" in same) await same.navigate(url).catch(() => {});
|
|
return;
|
|
}
|
|
await self.clients.openWindow(url);
|
|
})(),
|
|
);
|
|
});
|