diff --git a/frontend/controller/serviceworkers/sw-primary.js b/frontend/controller/serviceworkers/sw-primary.js index b6482a234..62b6a0cb5 100644 --- a/frontend/controller/serviceworkers/sw-primary.js +++ b/frontend/controller/serviceworkers/sw-primary.js @@ -66,6 +66,11 @@ self.addEventListener('message', function (event) { } }) +// Handle clicks on notifications issued via registration.showNotification(). +self.addEventListener('notificationclick', event => { + console.debug('[sw] Notification clicked:', event.notification) +}) + self.addEventListener('push', function (event) { // PushEvent reference: https://developer.mozilla.org/en-US/docs/Web/API/PushEvent diff --git a/frontend/model/contracts/shared/nativeNotification.js b/frontend/model/contracts/shared/nativeNotification.js index f32021be7..adbf411a6 100644 --- a/frontend/model/contracts/shared/nativeNotification.js +++ b/frontend/model/contracts/shared/nativeNotification.js @@ -31,10 +31,22 @@ export function makeNotification ({ title, body, icon, path }: { title: string, body: string, icon?: string, path?: string }): void { if (Notification?.permission === 'granted' && sbp('state/vuex/settings').notificationEnabled) { - const notification = new Notification(title, { body, icon }) - if (path) { - notification.onclick = function (event) { - sbp('controller/router').push({ path }).catch(console.warn) + try { + const notification = new Notification(title, { body, icon }) + if (path) { + notification.onclick = (event) => { + sbp('controller/router').push({ path }).catch(console.warn) + } + } + } catch { + try { + // FIXME: find a cross-browser way to pass the 'path' parameter when the notification is clicked. + navigator.serviceWorker?.ready.then(registration => { + // $FlowFixMe + registration.showNotification(title, { body, icon }) + }).catch(console.warn) + } catch (error) { + console.error('makeNotification: ', error.message) } } }