|
1 | | -const {UseServiceWorker, AppSubUrl, AppVer} = window.config; |
2 | | -const cachePrefix = 'static-cache-v'; // actual version is set in the service worker script |
3 | | - |
4 | 1 | async function unregister() { |
| 2 | + if (!('serviceWorker' in navigator)) return; |
5 | 3 | const registrations = await navigator.serviceWorker.getRegistrations(); |
6 | 4 | await Promise.all(registrations.map((registration) => { |
7 | 5 | return registration.active && registration.unregister(); |
8 | 6 | })); |
9 | 7 | } |
10 | 8 |
|
11 | 9 | async function invalidateCache() { |
| 10 | + if (!caches || !caches.keys) return; |
12 | 11 | const cacheKeys = await caches.keys(); |
13 | 12 | await Promise.all(cacheKeys.map((key) => { |
14 | | - return key.startsWith(cachePrefix) && caches.delete(key); |
| 13 | + return key.startsWith('static-cache-v') && caches.delete(key); |
15 | 14 | })); |
16 | 15 | } |
17 | 16 |
|
18 | | -async function checkCacheValidity() { |
19 | | - const cacheKey = AppVer; |
20 | | - const storedCacheKey = localStorage.getItem('staticCacheKey'); |
21 | | - |
22 | | - // invalidate cache if it belongs to a different gitea version |
23 | | - if (cacheKey && storedCacheKey !== cacheKey) { |
24 | | - await invalidateCache(); |
25 | | - localStorage.setItem('staticCacheKey', cacheKey); |
26 | | - } |
27 | | -} |
28 | | - |
29 | 17 | export default async function initServiceWorker() { |
30 | | - if (!('serviceWorker' in navigator)) return; |
31 | | - |
32 | | - if (UseServiceWorker) { |
33 | | - try { |
34 | | - // normally we'd serve the service worker as a static asset from StaticUrlPrefix but |
35 | | - // the spec strictly requires it to be same-origin so it has to be AppSubUrl to work |
36 | | - await Promise.all([ |
37 | | - checkCacheValidity(), |
38 | | - navigator.serviceWorker.register(`${AppSubUrl}/serviceworker.js`), |
39 | | - ]); |
40 | | - } catch (err) { |
41 | | - console.error(err); |
42 | | - await Promise.all([ |
43 | | - invalidateCache(), |
44 | | - unregister(), |
45 | | - ]); |
46 | | - } |
47 | | - } else { |
48 | | - await Promise.all([ |
49 | | - invalidateCache(), |
50 | | - unregister(), |
51 | | - ]); |
52 | | - } |
| 18 | + // we once had a service worker, if it's present, remove it and wipe its cache |
| 19 | + await Promise.all([ |
| 20 | + invalidateCache(), |
| 21 | + unregister(), |
| 22 | + ]); |
53 | 23 | } |
0 commit comments