2020-05-22 03:45:34 +02:00
|
|
|
const {UseServiceWorker, AppSubUrl, AppVer} = window.config;
|
2020-05-24 09:36:40 +02:00
|
|
|
const cachePrefix = 'static-cache-v'; // actual version is set in the service worker script
|
2020-05-22 03:45:34 +02:00
|
|
|
|
|
|
|
async function unregister() {
|
2020-05-24 09:36:40 +02:00
|
|
|
const registrations = await navigator.serviceWorker.getRegistrations();
|
|
|
|
await Promise.all(registrations.map((registration) => {
|
|
|
|
return registration.active && registration.unregister();
|
|
|
|
}));
|
2020-05-22 03:45:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async function invalidateCache() {
|
2020-05-24 09:36:40 +02:00
|
|
|
const cacheKeys = await caches.keys();
|
|
|
|
await Promise.all(cacheKeys.map((key) => {
|
|
|
|
return key.startsWith(cachePrefix) && caches.delete(key);
|
|
|
|
}));
|
2020-05-22 03:45:34 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
async function checkCacheValidity() {
|
|
|
|
const cacheKey = AppVer;
|
|
|
|
const storedCacheKey = localStorage.getItem('staticCacheKey');
|
|
|
|
|
|
|
|
// invalidate cache if it belongs to a different gitea version
|
|
|
|
if (cacheKey && storedCacheKey !== cacheKey) {
|
2020-05-24 09:36:40 +02:00
|
|
|
await invalidateCache();
|
2020-05-22 03:45:34 +02:00
|
|
|
localStorage.setItem('staticCacheKey', cacheKey);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default async function initServiceWorker() {
|
|
|
|
if (!('serviceWorker' in navigator)) return;
|
|
|
|
|
|
|
|
if (UseServiceWorker) {
|
|
|
|
try {
|
2021-05-08 16:27:25 +02:00
|
|
|
// normally we'd serve the service worker as a static asset from AssetUrlPrefix but
|
2020-05-24 09:36:40 +02:00
|
|
|
// the spec strictly requires it to be same-origin so it has to be AppSubUrl to work
|
|
|
|
await Promise.all([
|
|
|
|
checkCacheValidity(),
|
2021-04-28 14:35:06 +02:00
|
|
|
navigator.serviceWorker.register(`${AppSubUrl}/assets/serviceworker.js`),
|
2020-05-24 09:36:40 +02:00
|
|
|
]);
|
2020-05-22 03:45:34 +02:00
|
|
|
} catch (err) {
|
|
|
|
console.error(err);
|
2020-05-24 09:36:40 +02:00
|
|
|
await Promise.all([
|
|
|
|
invalidateCache(),
|
|
|
|
unregister(),
|
|
|
|
]);
|
2020-05-22 03:45:34 +02:00
|
|
|
}
|
|
|
|
} else {
|
2020-05-24 09:36:40 +02:00
|
|
|
await Promise.all([
|
|
|
|
invalidateCache(),
|
|
|
|
unregister(),
|
|
|
|
]);
|
2020-05-22 03:45:34 +02:00
|
|
|
}
|
|
|
|
}
|