push notifications working again

This commit is contained in:
Dobromir Popov
2024-05-07 10:48:02 +03:00
parent ceb686701e
commit 201399bc7a
2 changed files with 61 additions and 2 deletions

View File

@ -58,8 +58,8 @@ const Notification = async (req, res) => {
}
if (req.method == 'POST') {
const { subscription, id, broadcast, title = 'Hello Web Push', message = 'Your web push notification is here!' } = req.body
if (req.method == 'POST') {//title = "ССС", message = "Ще получите уведомление по този начин.")
const { subscription, id, broadcast, title = 'ССОМ', message = 'Ще получавате уведомления така.' } = req.body
if (broadcast) {
await broadcastPush(title, message)
res.statusCode = 200

59
worker/index.js Normal file
View File

@ -0,0 +1,59 @@
'use strict'
console.log('SW /worker/index.js Loaded...')
self.addEventListener('fetch', (event) => {
try {
if (event.request.url.includes('/api/auth/callback/')) {
// Use network only strategy for auth routes, or bypass SW completely
event.respondWith(fetch(event.request));
return;
}
// other caching strategies...
} catch (error) {
console.error(error)
}
});
self.addEventListener('push', function (event) {
console.log('SW: New push message', event)
if (!(self.Notification && self.Notification.permission === 'granted')) {
return
}
const data = JSON.parse(event.data.text())
event.waitUntil(
registration.showNotification(data.title, {
body: data.message,
icon: '/icons/android-chrome-192x192.png'
})
)
})
self.addEventListener('notificationclick', function (event) {
console.log('Notification click: tag', event.notification.tag)
event.notification.close()
event.waitUntil(
clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (clientList) {
if (clientList.length > 0) {
let client = clientList[0]
for (let i = 0; i < clientList.length; i++) {
if (clientList[i].focused) {
client = clientList[i]
}
}
return client.focus()
}
return clients.openWindow('/')
})
)
})
// self.addEventListener('pushsubscriptionchange', function(event) {
// event.waitUntil(
// Promise.all([
// Promise.resolve(event.oldSubscription ? deleteSubscription(event.oldSubscription) : true),
// Promise.resolve(event.newSubscription ? event.newSubscription : subscribePush(registration))
// .then(function(sub) { return saveSubscription(sub) })
// ])
// )
// })