62 lines
2.0 KiB
JavaScript
62 lines
2.0 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) => {
|
|
event.notification.close()
|
|
|
|
// Открытие URL из данных уведомления
|
|
event.waitUntil(
|
|
clients.matchAll({ type: 'window' }).then((clientList) => {
|
|
for (const client of clientList) {
|
|
if (client.url === event.notification.data.url && 'focus' in client) {
|
|
console.log('клик на уведомление', event.notification.tag)
|
|
|
|
return Promise.all([
|
|
client.focus(),
|
|
client.postMessage({
|
|
type: 'notificationClick',
|
|
tag: event.notification.tag,
|
|
payload: event.notification.payload,
|
|
}),
|
|
])
|
|
}
|
|
}
|
|
if (clients.openWindow) {
|
|
return clients.openWindow(event.notification.data.url)
|
|
}
|
|
}),
|
|
)
|
|
})
|