self.addEventListener('install', (event) => { console.log('install event:', event) // The promise that skipWaiting() returns can be safely ignored. self.skipWaiting() // Perform any other actions required for your // service worker to install, potentially inside // of event.waitUntil(); }) 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) }), ) })