so i'm new to webpush and push notifications. I've used a tutorial to get me up and running and in the whole it is working fine. the bit that i am trying to work on is sending a custom notification.
in my index.js for node i have this:
//route to test send notification
app.get('/webapp/send-notification', (req, res) => {
const subscription = dummyDb.subscription //get subscription from your databse here.
const message = 'Hello World'
sendNotification(subscription, message)
res.json({ message: 'message sent' })
})
Which is working fine, but each time i run it i get 'hello world' (which is what i expect). How do i set it up to change the message? If i try changing it then restarting node.js it seems to throw an error if i try to send it before i have refreshed the website (and by that i mean delete the service worker to get another subscription). i'm thinking there must be a way to create a basic html form with a textbox that contains the message that i want to send which on submit passes to this form to send the message.
this is (i think) the relevant code from the service worker file (although am happy to post the whole file):
self.addEventListener('push', function(event) {
if (event.data) {
console.log('Push event!! ', event.data.text())
showLocalNotification('Example Website', event.data.text(), self.registration)
} else {
console.log('Push event but no data')
}
})
const showLocalNotification = (title, body, swRegistration) => {
const options = {
body,
// here you can add more properties like icon, image, vibrate, etc.
}
swRegistration.showNotification(title, options)
}
Is it possible to set something up like the above? I feel like it is possible but i have something wrong in my configuration file somewhere which allows this, or because i have followed a basic tutorial my website is not as efficient as it could be.
event.data. See thepushevent in this service worker for example: pushpad.xyz/service-worker.js First you read the data attached to the push message and then you display the notification using the contents of the push message.