javascripthtmlpush-notificationweb-pushpush-api

Use data from Push in Web Push Notifications


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.


Solution

  • There are two ways:

    1. Push payload (example https://serviceworke.rs/push-payload.html). This is more complex and is currently only supported in Firefox and chrome v50. You can attach a payload to a push message and access it through the data property of the event (https://developer.mozilla.org/en-US/docs/Web/API/PushMessageData).

    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,
          })
        );
    
    1. 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,
          })
        )
      );