opensmtpd-filter-sake/pwa/sw.js

45 lines
1.3 KiB
JavaScript
Raw Normal View History

2023-07-23 15:06:57 +02:00
const sw_version = '0.1.0';
const cache_name = `sake-v${sw_version}`;
const cached_files = [
2023-07-23 17:39:49 +02:00
'/',
2023-07-23 15:06:57 +02:00
'/app.js',
'/index.html',
'/vendor/base32.min.js',
'/vendor/base32.min.js.map',
'/vendor/sha256.min.js',
];
function log_message(msg) {
console.log(`[Service Worker] v${sw_version}: ${msg}`);
}
2023-07-23 17:55:42 +02:00
self.addEventListener('install', (event) => {
2023-07-23 17:41:19 +02:00
log_message('Installed');
self.skipWaiting();
2023-07-23 17:55:42 +02:00
event.waitUntil(caches.open(cache_name).then((cache) => {
2023-07-23 15:06:57 +02:00
log_message('Caching all');
2023-07-23 17:41:19 +02:00
return cache.addAll(cached_files);
}));
2023-07-23 15:06:57 +02:00
});
2023-07-23 17:55:42 +02:00
self.addEventListener('fetch', (event) => {
if (!(event.request.url.startsWith('https:') || event.request.url.startsWith('http:'))) {
log_message(`Fetching resource failed: invalid protocol: ${event.request.url}`);
2023-07-23 15:06:57 +02:00
return;
}
2023-07-23 17:55:42 +02:00
event.respondWith((async () => {
log_message(`Fetching resource: ${event.request.url}`);
const cache_promise = await caches.match(event.request);
2023-07-23 15:06:57 +02:00
if (cache_promise) {
2023-07-23 17:55:42 +02:00
log_message(`Resource retrieved from cache: ${event.request.url}`);
2023-07-23 15:06:57 +02:00
return cache_promise;
}
2023-07-23 17:55:42 +02:00
const fetch_promise = await fetch(event.request);
2023-07-23 15:06:57 +02:00
const cache = await caches.open(cache_name);
2023-07-23 17:55:42 +02:00
log_message(`Caching new resource: ${event.request.url}`);
cache.put(event.request, fetch_promise.clone());
2023-07-23 15:06:57 +02:00
return fetch_promise;
})());
});