From 67ec07ac195f26063aba7601262fafb600bc3b16 Mon Sep 17 00:00:00 2001 From: Hangzhi Yu <hangzhi@protonmail.com> Date: Thu, 31 Dec 2020 01:24:41 +0100 Subject: [PATCH] Add simple message that is shown whenever a page is served from the PWA cache Apply 1 suggestion(s) to 1 file(s) dsf --- aleksis/core/static/js/main.js | 8 ++++++++ aleksis/core/static/js/serviceworker.js | 13 ++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/aleksis/core/static/js/main.js b/aleksis/core/static/js/main.js index 615f8b287..e7a58f3ff 100644 --- a/aleksis/core/static/js/main.js +++ b/aleksis/core/static/js/main.js @@ -110,3 +110,11 @@ $(document).ready(function () { el.addClass("closed").removeClass("opened"); }); }); + +// Show notice if serviceworker broadcasts that the current page comes from its cache +const channel = new BroadcastChannel("cache-or-not"); +channel.addEventListener("message", event => { + if ((event.data) && !($("#cache-alert").length)) { + $("main").prepend('<div id="cache-alert" class="alert warning"><p><i class="material-icons left">warning</i>' + gettext("This page may contain outdated information since there is no internet connection.") + '</p> </div>') + } +}); diff --git a/aleksis/core/static/js/serviceworker.js b/aleksis/core/static/js/serviceworker.js index 818e27cb7..25844bdfe 100644 --- a/aleksis/core/static/js/serviceworker.js +++ b/aleksis/core/static/js/serviceworker.js @@ -5,6 +5,10 @@ const CACHE = 'aleksis-cache'; const offlineFallbackPage = 'offline/'; +const channel = new BroadcastChannel('cache-or-not'); + +var comesFromCache = false; + self.addEventListener("install", function (event) { console.log("[AlekSIS PWA] Install Event processing."); @@ -28,7 +32,8 @@ self.addEventListener("activate", function (event) { // If any fetch fails, it will look for the request in the cache and serve it from there first self.addEventListener("fetch", function (event) { if (event.request.method !== "GET") return; - networkFirstFetch(event); + networkFirstFetch(event) + if (comesFromCache) channel.postMessage(true); }); function networkFirstFetch(event) { @@ -38,6 +43,7 @@ function networkFirstFetch(event) { // If request was successful, add or update it in the cache console.log("[AlekSIS PWA] Network request successful."); event.waitUntil(updateCache(event.request, response.clone())); + comesFromCache = false; return response; }) .catch(function (error) { @@ -56,11 +62,12 @@ function fromCache(event) { .then(function (matching) { if (!matching || matching.status === 404) { console.log("[AlekSIS PWA] Cache request failed. Serving offline fallback page."); + comesFromCache = false; // Use the precached offline page as fallback return caches.match(offlineFallbackPage) } - - return matching; + comesFromCache = true; + return matching }); }); } -- GitLab