I am trying to setup a demo for Web Push Notifications using Service Workers. In the service worker, sw.js, I have the following code.
var title = 'Yay a message.';
var body = 'We have received a push message.';
var icon = 'icon.png';
var tag = 'simple-push-demo-notification-tag';
console.log("Hello!");
self.addEventListener('push', function(event) {
event.waitUntil(
self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag
})
);
});
This works okay. I wish to receive data that I have sent with my push cURL
request like title
and more. Is there any way to get all that data here in this waitUntil
method?
Any help is highly appreciated.
There are two ways:
The payload needs to be encrypted (https://datatracker.ietf.org/doc/html/draft-thomson-webpush-encryption-01), using a library to take care of the encryption details is highly suggested (e.g. for Node.js https://github.com/marco-c/web-push).
The push event handler in this case would be (assuming the payload is sent as a JSON message):
var data = event.data.json();
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon,
tag: data.tag,
})
);
A GET request to your server to get the data. For example, assuming that your server returns a JSON response:
event.waitUntil(
fetch('someURL')
.then(response => response.json())
.then(data =>
self.registration.showNotification(data.title, {
body: data.body,
icon: data.icon,
tag: data.tag,
})
)
);