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.ready.then(registration => {
registration.active?.postMessage({
msg: 'initialize',
type: 'initialize',
lang,
});

View File

@ -161,24 +161,14 @@ self.addEventListener('notificationclose', <K extends keyof pushNotificationData
self.addEventListener('message', (ev: ServiceWorkerGlobalScopeEventMap['message']) => {
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') {
// E.g. '[object Array]' → 'array'
const otype = Object.prototype.toString.call(ev.data).slice(8, -1).toLowerCase();
if (otype === 'object') {
if (ev.data.msg === 'initialize') {
switch (ev.data.type) {
case 'initialize':
swLang.setLang(ev.data.lang);
}
break;
case 'notification':
createNotification(ev.data);
break;
}
}
})());