summaryrefslogtreecommitdiffstats
path: root/web_src/js/features/serviceworker.js
blob: a8fd2d41df83316cff4add96ab4c46524361999b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
const {UseServiceWorker, AppSubUrl, AppVer} = window.config;
const cacheName = 'static-cache-v2';

async function unregister() {
  for (const registration of await navigator.serviceWorker.getRegistrations()) {
    const serviceWorker = registration.active;
    if (!serviceWorker) continue;
    registration.unregister();
  }
}

async function invalidateCache() {
  await caches.delete(cacheName);
}

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) {
    invalidateCache();
    localStorage.setItem('staticCacheKey', cacheKey);
  }
}

export default async function initServiceWorker() {
  if (!('serviceWorker' in navigator)) return;

  if (UseServiceWorker) {
    await checkCacheValidity();
    try {
      await navigator.serviceWorker.register(`${AppSubUrl}/serviceworker.js`);
    } catch (err) {
      console.error(err);
      await invalidateCache();
      await unregister();
    }
  } else {
    await invalidateCache();
    await unregister();
  }
}