Files
hereconnect/apps/frontend/public/service-worker.js
T
ti 75be87c144
Main daploy / deploy (push) Successful in 45s
test web push
2024-11-21 16:11:23 +02:00

75 lines
2.4 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)
},
(e) => {
console.error('Notification ошибка создания', e)
},
),
)
} 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('notificationclick', (event) => {
console.log('клик на уведомление', event.notification)
event.notification.close()
// Открытие 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 === event.notification.data.url && '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('новое окно')
return clients.openWindow(event.notification.data.url).then((client) => {
if (client) {
return client.focus()
}
console.log('новое окно не открылось')
})
}
})
.catch((error) => {
console.error(error)
}),
)
})