From 5af6ab1045cf58bf8f37449ac51e33b80aaf8b68 Mon Sep 17 00:00:00 2001
From: Fabio Manganiello <fabio@manganiello.tech>
Date: Mon, 31 Mar 2025 12:24:10 +0200
Subject: [PATCH] Added PWA builder

---
 frontend/index.html                          |  2 ++
 frontend/public/js/pwabuilder-sw-register.js | 15 +++++++++++
 frontend/public/js/pwabuilder-sw.js          | 27 ++++++++++++++++++++
 3 files changed, 44 insertions(+)
 create mode 100644 frontend/public/js/pwabuilder-sw-register.js
 create mode 100644 frontend/public/js/pwabuilder-sw.js

diff --git a/frontend/index.html b/frontend/index.html
index 6312662..bea8508 100644
--- a/frontend/index.html
+++ b/frontend/index.html
@@ -5,6 +5,8 @@
     <link rel="icon" href="/favicon.ico">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <title>GPS Tracker</title>
+    <!-- PWA builder -->
+    <script type="module" src="/js/pwabuilder-sw-register.js"></script>
   </head>
   <body>
     <div id="app"></div>
diff --git a/frontend/public/js/pwabuilder-sw-register.js b/frontend/public/js/pwabuilder-sw-register.js
new file mode 100644
index 0000000..1f7ebef
--- /dev/null
+++ b/frontend/public/js/pwabuilder-sw-register.js
@@ -0,0 +1,15 @@
+// This is the "Background Sync" service worker
+
+// Add this below content to your HTML page inside a <script type="module"></script> tag, or add the js file to your page at the very top to register service worker
+// If you get an error about not being able to import, double check that you have type="module" on your <script /> tag
+
+/*
+ This code uses the pwa-update web component https://github.com/pwa-builder/pwa-update to register your service worker,
+ tell the user when there is an update available and let the user know when your PWA is ready to use offline.
+*/
+
+import 'https://cdn.jsdelivr.net/npm/@pwabuilder/pwaupdate';
+
+const el = document.createElement('pwa-update');
+document.body.appendChild(el);
+
diff --git a/frontend/public/js/pwabuilder-sw.js b/frontend/public/js/pwabuilder-sw.js
new file mode 100644
index 0000000..c06bca2
--- /dev/null
+++ b/frontend/public/js/pwabuilder-sw.js
@@ -0,0 +1,27 @@
+// This is the "Offline copy of assets" service worker
+
+const CACHE = "pwabuilder-offline";
+const QUEUE_NAME = "bgSyncQueue";
+
+importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');
+
+self.addEventListener("message", (event) => {
+  if (event.data && event.data.type === "SKIP_WAITING") {
+    self.skipWaiting();
+  }
+});
+
+const bgSyncPlugin = new workbox.backgroundSync.BackgroundSyncPlugin(QUEUE_NAME, {
+  maxRetentionTime: 24 * 60 // Retry for max of 24 Hours (specified in minutes)
+});
+
+workbox.routing.registerRoute(
+  new RegExp('/*'),
+  new workbox.strategies.StaleWhileRevalidate({
+    cacheName: CACHE,
+    plugins: [
+      bgSyncPlugin
+    ]
+  })
+);
+