Implement service worker offline page

Also, make sure it can be translated.
This commit is contained in:
N-Pex 2025-12-22 12:31:56 +01:00
parent 7cec56fb50
commit af96e3db5f
9 changed files with 601 additions and 115 deletions

164
public/offline.html Normal file
View file

@ -0,0 +1,164 @@
<html>
<head>
<meta charset="UTF-8">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
<script lang="javascript">
const STORE_KEY_USER = `convene_${window.location.hostname}_user`;
const STORE_KEY_SETTINGS = `convene_${window.location.hostname}_settings`;
let windowProxy = null;
function updateNetworkState() {
if (navigator.onLine) {
document.body.classList.remove("offline");
} else {
document.body.classList.add("offline");
}
}
window.addEventListener("load", (event) => {
updateNetworkState();
});
window.addEventListener("offline", (e) => {
updateNetworkState();
});
window.addEventListener("online", (e) => {
updateNetworkState();
});
function go() {
if (navigator.onLine) {
windowProxy = window.open("<!--MIRROR_URL-->/#/?migrate=1", "_blank");
}
}
window.addEventListener("message", function (e) {
// if (e.origin !== origin) { // TODO - What should we check here?
// return
// }
try {
const data = JSON.parse(e.data);
if (data !== null && data.cmd == "getMigrationData") {
let migrationInfo = {
};
if (window.localStorage.getItem(STORE_KEY_USER)) {
migrationInfo.type = "local";
migrationInfo.user = window.localStorage.getItem(STORE_KEY_USER);
migrationInfo.settings = window.localStorage.getItem(STORE_KEY_SETTINGS);
} else {
migrationInfo.type = "session";
migrationInfo.user = window.sessionStorage.getItem(STORE_KEY_USER);
migrationInfo.settings = window.sessionStorage.getItem(STORE_KEY_SETTINGS);
}
if (migrationInfo.user) {
try {
const user = JSON.parse(migrationInfo.user);
delete user.access_token;
delete user.device_id;
migrationInfo.user = JSON.stringify(user);
} catch (error) { }
}
event.source.postMessage(JSON.stringify(migrationInfo), event.origin);
} else if (data !== null && data.cmd == "migrationDone") {
if (windowProxy) {
windowProxy.close();
window.location.href = "<!--MIRROR_URL-->/#/";
}
}
} catch (error) {
}
});
</script>
<style>
body {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.title {
font-family: "Inter", sans-serif;
font-weight: 700;
font-style: Bold;
font-size: 16px;
leading-trim: NONE;
line-height: 125%;
letter-spacing: 0.4px;
text-align: center;
vertical-align: middle;
}
.message {
font-family: "Inter", sans-serif;
font-weight: 400;
font-style: normal;
font-size: 16px;
leading-trim: NONE;
line-height: 125%;
letter-spacing: 0.4px;
text-align: center;
vertical-align: middle;
}
button {
margin-top: 16px;
height: 40px;
border: 1px solid black;
border-radius: 20px;
background-color: white;
padding: 8px 16px;
font-family: "Poppins", sans-serif;
font-weight: 600;
font-style: SemiBold;
font-size: 14px;
leading-trim: NONE;
line-height: 18px;
letter-spacing: 0.34px;
text-align: center;
vertical-align: middle;
text-transform: uppercase;
}
button:hover {
opacity: 0.8;
cursor: pointer;
}
.offline-message {
margin-top: 40px;
visibility: hidden;
}
.offline .offline-message {
visibility: visible;
}
</style>
</head>
<body>
<div class="container">
<div class="title"><!--OFFLINE_TITLE_START-->Having trouble connecting?<!--OFFLINE_TITLE_END--></div>
<div class="message"><!--OFFLINE_MESSAGE_START-->Redirect to an alternate link to join the room<!--OFFLINE_MESSAGE_END--></div>
<button onclick="go()"><!--OFFLINE_REDIRECT_START-->Redirect me<!--OFFLINE_REDIRECT_END--></button>
<div class="offline-message">You are offline</div>
</div>
</body>
</html>

View file

@ -1,5 +1,19 @@
var periodicSyncNewMsgReminderText;
const OFFLINE_CACHE = `offline`;
const offlineCacheFiles = ['offline.html','config.json'];
// on install we download the routes we want to cache for offline
self.addEventListener('install', evt => evt.waitUntil(caches.open(OFFLINE_CACHE).then(cache => {
console.log("SW Caching offline files");
self.skipWaiting();
return cache.addAll(offlineCacheFiles);
})));
self.addEventListener("activate", event => {
event.waitUntil(clients.claim());
});
// Notification click event listener
self.addEventListener("notificationclick", (e) => {
e.notification.close();
@ -40,3 +54,88 @@ self.addEventListener('periodicsync', (event) => {
event.waitUntil(checkNewMessages());
}
});
self.addEventListener("fetch", (event) => {
if (event.request.mode === 'navigate') {
return event.respondWith(
fetch(event.request).catch((e) => {
console.log("OFFLINE, serve offline page", e);
return serveOfflinePage();
}));
} else if (event.request.url.endsWith("config.json")) {
return fetch(event.request)
.then((response) => {
console.log("Caching a new version of config.json");
let responseClone = response.clone();
caches
.open(OFFLINE_CACHE)
.then((cache) => cache.put(event.request, responseClone));
return response;
})
}
});
async function serveOfflinePage() {
let mirrorUrl = null;
const rConfig = await caches.match("config.json", { cacheName: OFFLINE_CACHE});
if (rConfig) {
const json = await rConfig.json();
const mirrors = json.mirrors;
if (mirrors && Array.isArray(mirrors) && mirrors.length > 0) {
mirrorUrl = json.mirrors[Math.floor(Math.random() * mirrors.length)];
}
}
const offlinePage = await caches.match("offline.html", { cacheName: OFFLINE_CACHE});
if (mirrorUrl && offlinePage) {
let text = await offlinePage.text();
text = text.replaceAll("<!--MIRROR_URL-->", mirrorUrl);
let title = undefined;
let message = undefined;
let redirect = undefined;
await new Promise((resolve, reject) => {
var open = indexedDB.open("ServiceWorker", 1);
open.onerror = function() {
resolve(false);
}
open.onsuccess = function() {
// Start a new transaction
var db = open.result;
var tx = db.transaction("offline_strings", "readonly");
var store = tx.objectStore("offline_strings");
var get1 = store.get("offline_title");
var get2 = store.get("offline_message");
var get3 = store.get("offline_redirect");
get1.onsuccess = function() {
title = get1.result.translation;
};
get2.onsuccess = function() {
message = get2.result.translation;
};
get3.onsuccess = function() {
redirect = get3.result.translation;
};
// Close the db when the transaction is done
tx.oncomplete = function() {
db.close();
resolve(true);
};
}
});
if (title) {
text = text.replaceAll(/<!--OFFLINE_TITLE_START-->(.*?)<!--OFFLINE_TITLE_END-->/g, title);
}
if (message) {
text = text.replaceAll(/<!--OFFLINE_MESSAGE_START-->(.*?)<!--OFFLINE_MESSAGE_END-->/g, message);
}
if (redirect) {
text = text.replaceAll(/<!--OFFLINE_REDIRECT_START-->(.*?)<!--OFFLINE_REDIRECT_END-->/g, redirect);
}
return new Response(text, { headers: {"content-type": "text/html"}});
}
throw new Error("Offline");
}