service worker: refactor message event handler

It is now possible for the client to trigger notifications "manually"
if push notifications are not configured on the server.
This commit is contained in:
Johann150 2022-11-12 18:27:44 +01:00
parent c34bebdf46
commit 1e8e551ee3
Signed by untrusted user: Johann150
GPG key ID: 9EE6577A2A06F8F1
2 changed files with 7 additions and 17 deletions

View file

@ -9,7 +9,7 @@ export async function initializeSw() {
navigator.serviceWorker.register('/sw.js', { scope: '/', type: 'classic' }); navigator.serviceWorker.register('/sw.js', { scope: '/', type: 'classic' });
navigator.serviceWorker.ready.then(registration => { navigator.serviceWorker.ready.then(registration => {
registration.active?.postMessage({ registration.active?.postMessage({
msg: 'initialize', type: 'initialize',
lang, lang,
}); });

View file

@ -161,24 +161,14 @@ self.addEventListener('notificationclose', <K extends keyof pushNotificationData
self.addEventListener('message', (ev: ServiceWorkerGlobalScopeEventMap['message']) => { self.addEventListener('message', (ev: ServiceWorkerGlobalScopeEventMap['message']) => {
ev.waitUntil((async () => { ev.waitUntil((async () => {
switch (ev.data) {
case 'clear':
// Cache Storage全削除
await caches.keys()
.then(cacheNames => Promise.all(
cacheNames.map(name => caches.delete(name))
));
return; // TODO
}
if (typeof ev.data === 'object') { if (typeof ev.data === 'object') {
// E.g. '[object Array]' → 'array' switch (ev.data.type) {
const otype = Object.prototype.toString.call(ev.data).slice(8, -1).toLowerCase(); case 'initialize':
if (otype === 'object') {
if (ev.data.msg === 'initialize') {
swLang.setLang(ev.data.lang); swLang.setLang(ev.data.lang);
} break;
case 'notification':
createNotification(ev.data);
break;
} }
} }
})()); })());