45 lines
1.1 KiB
TypeScript
45 lines
1.1 KiB
TypeScript
import { precacheAndRoute } from 'workbox-precaching'
|
|||
|
|
|
||
|
|
declare let self: ServiceWorkerGlobalScope
|
||
|
|
|
||
|
|
interface PushPayload {
|
||
|
|
title?: string
|
||
|
|
body?: string
|
||
|
|
conversation_id?: number
|
||
|
|
message_id?: number
|
||
|
|
}
|
||
|
|
|
||
|
|
precacheAndRoute(self.__WB_MANIFEST)
|
||
|
|
|
||
|
|
self.addEventListener('push', (event) => {
|
||
|
|
if (!event.data) return
|
||
|
|
let payload: PushPayload
|
||
|
|
try {
|
||
|
|
payload = event.data.json() as PushPayload
|
||
|
|
} catch {
|
||
|
|
payload = { body: event.data.text() }
|
||
|
|
}
|
||
|
|
const title = payload.title ?? 'Пульс'
|
||
|
|
const body = payload.body ?? 'Новое сообщение'
|
||
|
|
event.waitUntil(
|
||
|
|
self.registration.showNotification(title, {
|
||
|
|
body,
|
||
|
|
icon: '/icon-192.png',
|
||
|
|
badge: '/icon-192.png',
|
||
|
|
data: { conversation_id: payload.conversation_id, message_id: payload.message_id },
|
||
|
|
}),
|
||
|
|
)
|
||
|
|
})
|
||
|
|
|
||
|
|
self.addEventListener('notificationclick', (event) => {
|
||
|
|
event.notification.close()
|
||
|
|
event.waitUntil(
|
||
|
|
self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clients) => {
|
||
|
|
for (const client of clients) {
|
||
|
|
if ('focus' in client) return client.focus()
|
||
|
|
}
|
||
|
|
return self.clients.openWindow('/')
|
||
|
|
}),
|
||
|
|
)
|
||
|
|
})
|