about summary refs log tree commit diff
path: root/BugMine.Web/wwwroot/sw-registrator.js
diff options
context:
space:
mode:
Diffstat (limited to 'BugMine.Web/wwwroot/sw-registrator.js')
-rw-r--r--BugMine.Web/wwwroot/sw-registrator.js41
1 files changed, 41 insertions, 0 deletions
diff --git a/BugMine.Web/wwwroot/sw-registrator.js b/BugMine.Web/wwwroot/sw-registrator.js
new file mode 100644
index 0000000..94b96b2
--- /dev/null
+++ b/BugMine.Web/wwwroot/sw-registrator.js
@@ -0,0 +1,41 @@
+// source: https://whuysentruit.medium.com/blazor-wasm-pwa-adding-a-new-update-available-notification-d9f65c4ad13
+
+window.updateAvailable = new Promise((resolve, reject) => {
+    if (!('serviceWorker' in navigator)) {
+        const errorMessage = `This browser doesn't support service workers`;
+        console.error(errorMessage);
+        reject(errorMessage);
+        return;
+    }
+
+    navigator.serviceWorker.register('/service-worker.js')
+        .then(registration => {
+            console.info(`Service worker registration successful (scope: ${registration.scope})`);
+
+            // detect updates every minute
+            setInterval(() => {
+                registration.update();
+            }, 5 * 1000); // 60000ms -> check each minute
+
+            registration.onupdatefound = () => {
+                const installingServiceWorker = registration.installing;
+                installingServiceWorker.onstatechange = () => {
+                    if (installingServiceWorker.state === 'installed') {
+                        resolve(!!navigator.serviceWorker.controller);
+                    }
+                }
+            };
+        })
+        .catch(error => {
+            console.error('Service worker registration failed with error:', error);
+            reject(error);
+        });
+});
+
+window.registerForUpdateAvailableNotification = (caller, methodName) => {
+    window.updateAvailable.then(isUpdateAvailable => {
+        if (isUpdateAvailable) {
+            caller.invokeMethodAsync(methodName).then();
+        }
+    });
+};
\ No newline at end of file