feat: add PWA support with service worker and install prompt

This commit is contained in:
Linus Rath
2026-04-03 04:39:19 +02:00
parent 081c865018
commit 5aad97d64e
6 changed files with 255 additions and 0 deletions
+62
View File
@@ -0,0 +1,62 @@
/* eslint-disable no-undef */
const CACHE_NAME = "bulwark-v1";
const STATIC_ASSETS = ["/", "/manifest.json"];
self.addEventListener("install", (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(STATIC_ASSETS);
})
);
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames
.filter((cacheName) => cacheName !== CACHE_NAME)
.map((cacheName) => caches.delete(cacheName))
);
})
);
self.clients.claim();
});
self.addEventListener("fetch", (event) => {
// Skip non-GET requests
if (event.request.method !== "GET") {
return;
}
// Skip API requests and external requests
if (
event.request.url.includes("/api/") ||
!event.request.url.startsWith(self.location.origin)
) {
return;
}
event.respondWith(
caches.match(event.request).then((response) => {
if (response) {
return response;
}
return fetch(event.request).then((response) => {
if (!response || response.status !== 200 || response.type === "error") {
return response;
}
const responseToCache = response.clone();
caches.open(CACHE_NAME).then((cache) => {
cache.put(event.request, responseToCache);
});
return response;
});
})
);
});