Files
privacy-tools/public/sw.js
T
2026-09-01 02:39:44 +02:00

55 lines
1.5 KiB
JavaScript

const CACHE_PREFIX = "privacy-tools-shell-";
const CACHE_NAME = CACHE_PREFIX + "0.1.0";
const CORE = ["./", "./manifest.webmanifest", "./favicon.svg"];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then(async (cache) => {
await cache.addAll(CORE);
const html = await (await fetch("./")).text();
const assets = [...html.matchAll(/(?:src|href)="(\.\/assets\/[^"]+)"/g)]
.map((match) => match[1])
.filter(Boolean);
await cache.addAll(assets);
}),
);
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches
.keys()
.then((keys) =>
Promise.all(
keys
.filter((key) => key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME)
.map((key) => caches.delete(key)),
),
)
.then(() => self.clients.claim()),
);
});
self.addEventListener("fetch", (event) => {
if (event.request.method !== "GET") return;
const url = new URL(event.request.url);
if (
url.origin !== self.location.origin ||
!url.pathname.startsWith(new URL(self.registration.scope).pathname)
)
return;
event.respondWith(
caches.match(event.request).then(
(cached) =>
cached ??
fetch(event.request).then((response) => {
if (response.ok) {
const copy = response.clone();
void caches
.open(CACHE_NAME)
.then((cache) => cache.put(event.request, copy));
}
return response;
}),
),
);
});