You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

serviceworker.js 1.6KB

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