2024-09-18 17:32:26 +03:00
|
|
|
importScripts('./assets/js/data/swconf.js');
|
2024-01-27 21:22:33 +03:00
|
|
|
|
|
|
|
const purge = swconf.purge;
|
2024-07-17 18:32:48 +03:00
|
|
|
const interceptor = swconf.interceptor;
|
2024-01-27 21:22:33 +03:00
|
|
|
|
|
|
|
function verifyUrl(url) {
|
2024-07-17 18:32:48 +03:00
|
|
|
const requestUrl = new URL(url);
|
|
|
|
const requestPath = requestUrl.pathname;
|
2024-01-27 21:22:33 +03:00
|
|
|
|
2024-07-17 18:32:48 +03:00
|
|
|
if (!requestUrl.protocol.startsWith('http')) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
for (const prefix of interceptor.urlPrefixes) {
|
|
|
|
if (requestUrl.href.startsWith(prefix)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for (const path of interceptor.paths) {
|
2024-01-27 21:22:33 +03:00
|
|
|
if (requestPath.startsWith(path)) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
self.addEventListener('install', (event) => {
|
|
|
|
if (purge) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
event.waitUntil(
|
|
|
|
caches.open(swconf.cacheName).then((cache) => {
|
|
|
|
return cache.addAll(swconf.resources);
|
|
|
|
})
|
|
|
|
);
|
|
|
|
});
|
|
|
|
|
|
|
|
self.addEventListener('activate', (event) => {
|
|
|
|
event.waitUntil(
|
|
|
|
caches.keys().then((keyList) => {
|
|
|
|
return Promise.all(
|
|
|
|
keyList.map((key) => {
|
|
|
|
if (purge) {
|
|
|
|
return caches.delete(key);
|
|
|
|
} else {
|
|
|
|
if (key !== swconf.cacheName) {
|
|
|
|
return caches.delete(key);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
);
|
|
|
|
})
|
|
|
|
);
|
|
|
|
});
|
|
|
|
|
|
|
|
self.addEventListener('message', (event) => {
|
|
|
|
if (event.data === 'SKIP_WAITING') {
|
|
|
|
self.skipWaiting();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
self.addEventListener('fetch', (event) => {
|
2024-04-29 18:27:41 +03:00
|
|
|
if (event.request.headers.has('range')) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-01-27 21:22:33 +03:00
|
|
|
event.respondWith(
|
|
|
|
caches.match(event.request).then((response) => {
|
|
|
|
if (response) {
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
|
|
|
return fetch(event.request).then((response) => {
|
|
|
|
const url = event.request.url;
|
|
|
|
|
|
|
|
if (purge || event.request.method !== 'GET' || !verifyUrl(url)) {
|
|
|
|
return response;
|
|
|
|
}
|
|
|
|
|
2024-05-11 05:29:14 +03:00
|
|
|
// See: <https://developers.google.com/web/fundamentals/primers/service-workers#cache_and_return_requests>
|
2024-01-27 21:22:33 +03:00
|
|
|
let responseToCache = response.clone();
|
|
|
|
|
|
|
|
caches.open(swconf.cacheName).then((cache) => {
|
|
|
|
cache.put(event.request, responseToCache);
|
|
|
|
});
|
|
|
|
return response;
|
|
|
|
});
|
|
|
|
})
|
|
|
|
);
|
|
|
|
});
|