Files
hereconnect/apps/frontend/public/service-worker.js
T
ti 458e5e34d8
Main daploy / deploy (push) Successful in 53s
update service worker
2024-11-21 16:51:51 +02:00

85 lines
2.7 KiB
JavaScript

self.addEventListener('push', (event) => {
const data = event.data.json()
console.log('Push событие получено:', data.type)
// Отображение уведомления
if (data.type === 'notification') {
event.waitUntil(
self.registration
.showNotification(data.notification.title, data.notification.options)
.then(() => {
console.log('Notification создан', data.notification.options.tag)
})
.catch((error) => {
console.error('Notification ошибка создания', error)
}),
)
} else if (data.type === 'cancelNotification') {
event.waitUntil(
self.registration
.getNotifications({ tag: data.notification.options.tag })
.then((notifications) => {
notifications.forEach((notification) => {
if (
notification.tag === data.notification.options.tag ||
notification.data.payload.tag === data.notification.options.data.payload.tag // удалить, если notification.tag поддерживают все
) {
notification.close()
console.log('Notification удален')
}
})
}),
)
}
})
self.addEventListener('notificationclose', function (event) {
const dismissedNotification = event.notification
console.log('dismissedNotification', dismissedNotification)
})
self.addEventListener('notificationclick', (event) => {
console.log('клик на уведомление', event.notification)
const urlToOpen = new URL(event.notification.data.url, self.location.origin).href
// Открытие URL из данных уведомления
event.waitUntil(
clients
.matchAll({ type: 'window', includeUncontrolled: true })
.then((clientList) => {
for (const client of clientList) {
console.log('client.url', client.url)
if (client.url === urlToOpen && 'focus' in client) {
console.log('фокус')
return Promise.all([
client.focus(),
client.postMessage({
type: 'notificationClick',
tag: event.notification.tag,
payload: event.notification.payload,
}),
])
}
}
if (clients.openWindow) {
console.log('новое окно', urlToOpen)
return clients.openWindow(urlToOpen).then((client) => {
if (client) {
return client.focus()
}
console.log('новое окно не открылось')
})
}
})
.then(() => {
return event.notification.close()
})
.catch((error) => {
console.error(error)
}),
)
})