From 2ae13f6ec42eb154a596ae0d9175f587d6ff310a Mon Sep 17 00:00:00 2001 From: Vasilii Mikhailovskii Date: Sun, 1 Dec 2024 22:30:40 +0200 Subject: [PATCH] support redirect in notifications --- apps/frontend/public/service-worker.js | 70 +++++++++++++++++++------- 1 file changed, 51 insertions(+), 19 deletions(-) diff --git a/apps/frontend/public/service-worker.js b/apps/frontend/public/service-worker.js index d3ec03a..3565a1e 100644 --- a/apps/frontend/public/service-worker.js +++ b/apps/frontend/public/service-worker.js @@ -56,42 +56,74 @@ self.addEventListener('notificationclose', function (event) { }) self.addEventListener('notificationclick', (event) => { - console.log('клик на уведомление', event.notification) + console.log('click to notification', event.notification) - const urlToOpen = new URL(event.notification.data.url, self.location.origin).href + event.notification.close() + + // const urlToOpen = new URL(event.notification.data.url, self.location.origin).href + + if (!event.notification.data.url) { + console.log('no urlToOpen') + return + } + + function getNotificationUrl(urlToOpen) { + return fetch(urlToOpen, { + redirect: 'manual', + method: 'HEAD', + cache: 'no-cache', + }) + .then((response) => { + console.log('response.url', response.url) + console.log('response.type', response.url) + if (response && response.type === 'opaqueredirect') { + const location = response.headers.get('location') + console.log('headers location', location) + return location + } + return response.url + }) + .catch((error) => { + console.debug('erro in getNotificationUrl', error) + return urlToOpen + }) + } // Открытие URL из данных уведомления event.waitUntil( - clients - .matchAll({ type: 'window', includeUncontrolled: true }) - .then((clientList) => { + Promise.all([ + getNotificationUrl(event.notification.data.url), + + clients.matchAll({ type: 'window', includeUncontrolled: true }), + ]) + .then(([urlToOpen, clientList]) => { for (const client of clientList) { console.log('client.url', client.url) if (client.url === urlToOpen && 'focus' in client) { - console.log('фокус') + console.log('focus') - return Promise.all([ - client.focus(), - client.postMessage({ - type: 'notificationClick', - tag: event.notification.tag, - payload: event.notification.payload, - }), - ]) + return client.focus() + // return Promise.all([ + // client.focus(), + // client.postMessage({ + // type: 'notificationClick', + // tag: event.notification.tag, + // payload: event.notification.payload, + // }), + // ]) } } if (clients.openWindow) { - console.log('новое окно', urlToOpen) + console.log('open new window', urlToOpen) return clients.openWindow(urlToOpen).then((client) => { if (!client) { - console.log('новое окно не открылось') + console.log('new window not opened') } }) + } else { + console.log('clients.openWindow not available') } }) - .then(() => { - return event.notification.close() - }) .catch((error) => { console.error(error) }),