Skip to content
Snippets Groups Projects
Commit 67ec07ac authored by Hangzhi Yu's avatar Hangzhi Yu
Browse files

Add simple message that is shown whenever a page is served from the PWA cache

Apply 1 suggestion(s) to 1 file(s)

dsf
parent 66fa1b79
No related branches found
No related tags found
No related merge requests found
Pipeline #5181 passed
......@@ -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>')
}
});
......@@ -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
});
});
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment