1
votes

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.

2

2 Answers

3
votes

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://tools.ietf.org/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,
      })
    );
    
  2. 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,
        })
      )
    );
    
0
votes

Wait until Chrome 49 comes out: Mar 8th, 2016

Like said in this article: https://www.chromestatus.com/features/5746279325892608, chrome will implement payloads