From 8ccbe2ebf149b3551542797b6b2942fcd9aea778 Mon Sep 17 00:00:00 2001 From: Nathan Woodburn Date: Wed, 29 Jan 2025 18:51:28 +1100 Subject: [PATCH] feat: Add service worker --- manifest.json => pwa/manifest.json | 0 pwa/sw.js | 53 ++++++++++++++++++++++++++++++ server.py | 10 +++--- templates/index.html | 7 +++- 4 files changed, 65 insertions(+), 5 deletions(-) rename manifest.json => pwa/manifest.json (100%) create mode 100644 pwa/sw.js diff --git a/manifest.json b/pwa/manifest.json similarity index 100% rename from manifest.json rename to pwa/manifest.json diff --git a/pwa/sw.js b/pwa/sw.js new file mode 100644 index 0000000..20cc77e --- /dev/null +++ b/pwa/sw.js @@ -0,0 +1,53 @@ +// This is the service worker with the combined offline experience (Offline page + Offline copy of pages) + +const CACHE = "pwabuilder-offline-page"; + +importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js'); + +const offlineFallbackPage = "404"; + +self.addEventListener("message", (event) => { + if (event.data && event.data.type === "SKIP_WAITING") { + self.skipWaiting(); + } +}); + +self.addEventListener('install', async (event) => { + event.waitUntil( + caches.open(CACHE) + .then((cache) => cache.add(offlineFallbackPage)) + ); +}); + +if (workbox.navigationPreload.isSupported()) { + workbox.navigationPreload.enable(); +} + +workbox.routing.registerRoute( + new RegExp('/*'), + new workbox.strategies.StaleWhileRevalidate({ + cacheName: CACHE + }) +); + +self.addEventListener('fetch', (event) => { + if (event.request.mode === 'navigate') { + event.respondWith((async () => { + try { + const preloadResp = await event.preloadResponse; + + if (preloadResp) { + return preloadResp; + } + + const networkResp = await fetch(event.request); + return networkResp; + } catch (error) { + + const cache = await caches.open(CACHE); + const cachedResp = await cache.match(offlineFallbackPage); + return cachedResp; + } + })()); + } +}); \ No newline at end of file diff --git a/server.py b/server.py index 808de22..10a8012 100644 --- a/server.py +++ b/server.py @@ -237,18 +237,20 @@ def manifest(): host = request.host # Read as json - with open("manifest.json") as file: + with open("pwa/manifest.json") as file: manifest = json.load(file) url = f"https://{host}" if host == "localhost:5000" or host == "127.0.0.1:5000": url = "http://127.0.0.1:5000" manifest["start_url"] = url - manifest["scope"] = url - - + manifest["scope"] = url return jsonify(manifest) +@app.route("/sw.js") +def pw(): + return send_from_directory("pwa", "sw.js") + # region Sol Links @app.route("/actions.json") diff --git a/templates/index.html b/templates/index.html index ebc2053..7c14be8 100644 --- a/templates/index.html +++ b/templates/index.html @@ -274,7 +274,12 @@ Check them out here!