sw-register.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. if ('serviceWorker' in navigator) {
  2. if (location.pathname.startsWith('/spoolbuddy')) {
  3. navigator.serviceWorker.getRegistrations().then((regs) => {
  4. if (regs.length > 0) {
  5. Promise.all([
  6. ...regs.map((r) => r.unregister()),
  7. caches.keys().then((names) => Promise.all(names.map((n) => caches.delete(n)))),
  8. ]).then(() => location.reload());
  9. }
  10. });
  11. } else {
  12. // Capture controller state at script-load. Used to decide whether a
  13. // subsequent `controllerchange` is a deploy-pickup (had a prior SW →
  14. // reload so the new bundle takes over) or a first install (no prior SW →
  15. // skip the reload; the in-flight React mount would otherwise race the
  16. // forced navigation, leaving the page wedged on a spinner. The previous
  17. // approach — `client.navigate(client.url)` from the SW's activate
  18. // handler — exhibited that race in Chromium and a waitUntil hang in
  19. // Firefox, both surfaced on every fresh demo subdomain).
  20. const hadController = !!navigator.serviceWorker.controller;
  21. let reloading = false;
  22. navigator.serviceWorker.addEventListener('controllerchange', () => {
  23. if (!hadController || reloading) return;
  24. reloading = true;
  25. location.reload();
  26. });
  27. window.addEventListener('load', () => {
  28. navigator.serviceWorker.register('/sw.js')
  29. .then((registration) => {
  30. console.log('SW registered:', registration.scope);
  31. })
  32. .catch((error) => {
  33. console.log('SW registration failed:', error);
  34. });
  35. });
  36. }
  37. }