service-worker-register.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. const serviceWorkerFileName = 'service-worker.js';
  2. const swInstalledEvent = 'installed';
  3. const staticCachePrefix = 'blazor-cache-v';
  4. const updateAlertMessage = 'Update available. Reload the page when convenient.';
  5. const blazorAssembly = 'BootstrapBlazor.Shared';
  6. const blazorInstallMethod = 'PWAInstallable';
  7. window.updateAvailable = new Promise(function (resolve, reject) {
  8. if ('serviceWorker' in navigator) {
  9. navigator.serviceWorker.register(serviceWorkerFileName)
  10. .then(function (registration) {
  11. console.log('Registration successful, scope is:', registration.scope);
  12. registration.onupdatefound = () => {
  13. const installingWorker = registration.installing;
  14. installingWorker.onstatechange = () => {
  15. switch (installingWorker.state) {
  16. case swInstalledEvent:
  17. if (navigator.serviceWorker.controller) {
  18. resolve(true);
  19. } else {
  20. resolve(false);
  21. }
  22. break;
  23. default:
  24. }
  25. };
  26. };
  27. })
  28. .catch(error =>
  29. console.log('Service worker registration failed, error:', error));
  30. }
  31. });
  32. window['updateAvailable']
  33. .then(isAvailable => {
  34. if (isAvailable) {
  35. alert(updateAlertMessage);
  36. }
  37. });
  38. function showAddToHomeScreen() {
  39. DotNet.invokeMethodAsync(blazorAssembly, blazorInstallMethod)
  40. .then(function () { }, function (er) { setTimeout(showAddToHomeScreen, 1000); });
  41. }
  42. window.BlazorPWA = {
  43. installPWA: function () {
  44. if (window.PWADeferredPrompt) {
  45. window.PWADeferredPrompt.prompt();
  46. window.PWADeferredPrompt.userChoice
  47. .then(function (choiceResult) {
  48. window.PWADeferredPrompt = null;
  49. });
  50. }
  51. }
  52. };
  53. window.addEventListener('beforeinstallprompt', function (e) {
  54. // Prevent Chrome 67 and earlier from automatically showing the prompt
  55. e.preventDefault();
  56. // Stash the event so it can be triggered later.
  57. window.PWADeferredPrompt = e;
  58. showAddToHomeScreen();
  59. });