From 43bb075849fe0d573c20c1baddb45cabf72833b6 Mon Sep 17 00:00:00 2001 From: Deluan Date: Tue, 13 Apr 2021 13:25:50 -0400 Subject: [PATCH] New service worker (#952) --- ui/public/navidrome-service-worker.js | 48 +++++++++++++++++++++++++++ ui/public/offline.html | 10 ++++++ ui/src/serviceWorker.js | 2 +- 3 files changed, 59 insertions(+), 1 deletion(-) create mode 100644 ui/public/navidrome-service-worker.js create mode 100644 ui/public/offline.html diff --git a/ui/public/navidrome-service-worker.js b/ui/public/navidrome-service-worker.js new file mode 100644 index 000000000..2cc12ab99 --- /dev/null +++ b/ui/public/navidrome-service-worker.js @@ -0,0 +1,48 @@ +// documentation: https://developers.google.com/web/tools/workbox/modules/workbox-sw +importScripts("https://storage.googleapis.com/workbox-cdn/releases/6.1.2/workbox-sw.js"); + +workbox.loadModule('workbox-core'); +workbox.loadModule('workbox-strategies'); +workbox.loadModule('workbox-routing'); +workbox.loadModule('workbox-navigation-preload'); + +workbox.core.clientsClaim(); +self.skipWaiting(); + +addEventListener('message', (event) => { + if (event.data && event.data.type === 'SKIP_WAITING') { + skipWaiting(); + } +}); + + +const CACHE_NAME = 'offline-html'; +// This assumes /offline.html is a URL for your self-contained +// (no external images or styles) offline page. +const FALLBACK_HTML_URL = './offline.html'; +// Populate the cache with the offline HTML page when the +// service worker is installed. +self.addEventListener('install', async (event) => { + event.waitUntil( + caches.open(CACHE_NAME) + .then((cache) => cache.add(FALLBACK_HTML_URL)) + ); +}); + +const networkOnly = new workbox.strategies.NetworkOnly(); +const navigationHandler = async (params) => { + try { + // Attempt a network request. + return await networkOnly.handle(params); + } catch (error) { + // If it fails, return the cached HTML. + return caches.match(FALLBACK_HTML_URL, { + cacheName: CACHE_NAME, + }); + } +}; + +// Register this strategy to handle all navigations. +workbox.routing.registerRoute( + new workbox.routing.NavigationRoute(navigationHandler) +); diff --git a/ui/public/offline.html b/ui/public/offline.html new file mode 100644 index 000000000..72f2d04ae --- /dev/null +++ b/ui/public/offline.html @@ -0,0 +1,10 @@ + + +Navidrome + +

+It looks like we are having trouble connecting. +
+Please check your internet connection and try again.

+ + \ No newline at end of file diff --git a/ui/src/serviceWorker.js b/ui/src/serviceWorker.js index 9d6cf1422..420ee107e 100644 --- a/ui/src/serviceWorker.js +++ b/ui/src/serviceWorker.js @@ -32,7 +32,7 @@ export function register(config) { } window.addEventListener('load', () => { - const swUrl = `${process.env.PUBLIC_URL}/service-worker.js` + const swUrl = `${process.env.PUBLIC_URL}/navidrome-service-worker.js` if (isLocalhost) { // This is running on localhost. Let's check if a service worker still exists or not.