From aa7870b2eae80a6dbdc1a92dc2429b1e66d3c1f7 Mon Sep 17 00:00:00 2001 From: Fuwn Date: Thu, 25 Jul 2024 02:55:38 -0700 Subject: fix(pwa): robust silent notifications --- src/service-worker.ts | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/src/service-worker.ts b/src/service-worker.ts index d7629073..21de63a2 100644 --- a/src/service-worker.ts +++ b/src/service-worker.ts @@ -114,7 +114,9 @@ sw.addEventListener('push', async (event: PushEvent) => { sw.registration.showNotification('due.moe', { body: `${recentNotifications[0].user.name}${recentNotifications[0].context}`, - icon: recentNotifications[0].user.avatar.large || '/favicon-196x196.png' + icon: recentNotifications[0].user.avatar.large || '/favicon-196x196.png', + // Ref. https://stackoverflow.com/a/50805868/14452787 + tag: 'notification-1' }); return; @@ -123,11 +125,17 @@ sw.addEventListener('push', async (event: PushEvent) => { console.error(error); } - event.waitUntil( - new Promise(() => { - // - }) - ); + // Ref. https://github.com/firebase/quickstart-js/issues/126#issuecomment-504081087 + return new Promise((resolve) => { + (resolve as unknown as () => void)(); + setTimeout(() => { + sw.registration.getNotifications().then((notifications) => { + notifications.forEach((notification) => { + if (notification.tag !== 'notification') notification.close(); + }); + }); + }, 10); + }); }); sw.addEventListener('notificationclick', (event: NotificationEvent) => { -- cgit v1.2.3