56 lines
2 KiB
JavaScript
56 lines
2 KiB
JavaScript
// Cosmo VPN PWA service worker: offline shell + Web Push (mailings and expiry reminders from the server).
|
|
const CACHE = "cosmo-shell-v1";
|
|
const SHELL = ["./", "app.js", "manifest.json", "icons/icon-192.png", "icons/icon-180.png"];
|
|
|
|
self.addEventListener("install", (e) => {
|
|
e.waitUntil(caches.open(CACHE).then((c) => c.addAll(SHELL)).then(() => self.skipWaiting()));
|
|
});
|
|
|
|
self.addEventListener("activate", (e) => {
|
|
e.waitUntil(
|
|
caches.keys()
|
|
.then((keys) => Promise.all(keys.filter((k) => k !== CACHE).map((k) => caches.delete(k))))
|
|
.then(() => self.clients.claim())
|
|
);
|
|
});
|
|
|
|
// Shell: network first (always fresh), cache as offline fallback. API calls are never cached.
|
|
self.addEventListener("fetch", (e) => {
|
|
const url = new URL(e.request.url);
|
|
if (e.request.method !== "GET" || url.origin !== location.origin || url.pathname.includes("/api/")) return;
|
|
e.respondWith(
|
|
fetch(e.request)
|
|
.then((resp) => {
|
|
const copy = resp.clone();
|
|
caches.open(CACHE).then((c) => c.put(e.request, copy));
|
|
return resp;
|
|
})
|
|
.catch(() => caches.match(e.request, { ignoreSearch: true }).then((r) => r || caches.match("./")))
|
|
);
|
|
});
|
|
|
|
self.addEventListener("push", (e) => {
|
|
let data = {};
|
|
try { data = e.data ? e.data.json() : {}; } catch (_) { data = { body: e.data && e.data.text() }; }
|
|
e.waitUntil(
|
|
self.registration.showNotification(data.title || "Cosmo VPN", {
|
|
body: data.body || "",
|
|
icon: "icons/icon-192.png",
|
|
badge: "icons/icon-192.png",
|
|
data: { url: data.url || "./" },
|
|
})
|
|
);
|
|
});
|
|
|
|
self.addEventListener("notificationclick", (e) => {
|
|
e.notification.close();
|
|
const target = new URL(e.notification.data && e.notification.data.url || "./", self.registration.scope).href;
|
|
e.waitUntil(
|
|
self.clients.matchAll({ type: "window", includeUncontrolled: true }).then((list) => {
|
|
for (const c of list) {
|
|
if (c.url.startsWith(self.registration.scope)) { c.navigate(target); return c.focus(); }
|
|
}
|
|
return self.clients.openWindow(target);
|
|
})
|
|
);
|
|
});
|