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