80 lines
2.3 KiB
JavaScript
80 lines
2.3 KiB
JavaScript
const CACHE_NAME = 'sysadmin-arcade-v1';
|
|
|
|
const PRECACHE_URLS = [
|
|
'./',
|
|
'./index.html',
|
|
'./games.json',
|
|
'./manifest.webmanifest',
|
|
'./games/uptime/uptime-incident-response.html',
|
|
'./games/uptime/manifest.webmanifest',
|
|
'./games/uptime/favicon/favicon.svg',
|
|
'./games/uptime/favicon/favicon.ico',
|
|
'./games/uptime/favicon/favicon-16.png',
|
|
'./games/uptime/favicon/favicon-32.png',
|
|
'./games/uptime/favicon/favicon-180.png',
|
|
'./games/uptime/favicon/favicon-192.png',
|
|
'./games/uptime/favicon/favicon-512.png'
|
|
];
|
|
|
|
const cacheUrl = (path) => new URL(path, self.registration.scope).href;
|
|
|
|
self.addEventListener('install', (event) => {
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME)
|
|
.then((cache) => cache.addAll(PRECACHE_URLS.map(cacheUrl)))
|
|
.then(() => self.skipWaiting())
|
|
);
|
|
});
|
|
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches.keys()
|
|
.then((keys) => Promise.all(
|
|
keys
|
|
.filter((key) => key !== CACHE_NAME)
|
|
.map((key) => caches.delete(key))
|
|
))
|
|
.then(() => self.clients.claim())
|
|
);
|
|
});
|
|
|
|
self.addEventListener('fetch', (event) => {
|
|
const { request } = event;
|
|
const url = new URL(request.url);
|
|
|
|
if (request.method !== 'GET' || url.origin !== self.location.origin) return;
|
|
|
|
if (request.mode === 'navigate') {
|
|
event.respondWith(
|
|
fetch(request)
|
|
.then((response) => {
|
|
const responseCopy = response.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(request, responseCopy));
|
|
return response;
|
|
})
|
|
.catch(async () => {
|
|
const fallback = url.pathname.includes('/games/uptime/')
|
|
? './games/uptime/uptime-incident-response.html'
|
|
: './index.html';
|
|
|
|
return await caches.match(request) || await caches.match(cacheUrl(fallback));
|
|
})
|
|
);
|
|
return;
|
|
}
|
|
|
|
event.respondWith(
|
|
caches.match(request).then((cachedResponse) => {
|
|
if (cachedResponse) return cachedResponse;
|
|
|
|
return fetch(request).then((response) => {
|
|
if (!response || response.status !== 200 || response.type !== 'basic') return response;
|
|
|
|
const responseCopy = response.clone();
|
|
caches.open(CACHE_NAME).then((cache) => cache.put(request, responseCopy));
|
|
return response;
|
|
});
|
|
})
|
|
);
|
|
});
|