From f449bfe2f1d77172aee0433f63ec4a82bcc7ea1e Mon Sep 17 00:00:00 2001 From: Henry Jameson Date: Thu, 9 Nov 2023 01:52:39 +0200 Subject: [PATCH] SW-to-window communication --- src/services/sw/sw.js | 8 ++++++-- src/sw.js | 6 +++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/services/sw/sw.js b/src/services/sw/sw.js index 3b62bac8..7de490fe 100644 --- a/src/services/sw/sw.js +++ b/src/services/sw/sw.js @@ -82,9 +82,13 @@ function sendSubscriptionToBackEnd (subscription, token, notificationVisibility) return responseData }) } -export function initServiceWorker () { +export async function initServiceWorker () { if (!isSWSupported()) return - getOrCreateServiceWorker() + await getOrCreateServiceWorker() + navigator.serviceWorker.addEventListener('message', (event) => { + console.log('SW MESSAGE', event) + // TODO actually act upon click (open drawer on mobile for now) + }) } export async function showDesktopNotification (content) { diff --git a/src/sw.js b/src/sw.js index 1b08fe69..b95d56a4 100644 --- a/src/sw.js +++ b/src/sw.js @@ -56,7 +56,6 @@ self.addEventListener('push', async (event) => { self.addEventListener('message', async (event) => { const { type, content } = event.data - console.log(event) if (type === 'desktopNotification') { const { title, ...rest } = content @@ -79,6 +78,11 @@ self.addEventListener('notificationclick', (event) => { event.notification.close() event.waitUntil(getWindowClients().then((list) => { + for (let i = 0; i < list.length; i++) { + const client = list[i] + client.postMessage({ type: 'notificationClicked', id: event.notification.tag }) + } + for (let i = 0; i < list.length; i++) { const client = list[i] if (state.lastFocused === null || client.id === state.lastFocused) {