googlearchive / web-push-encryption

[Deprecated] Encryption Utilities for Web Push protocol
Apache License 2.0
84 stars 23 forks source link

How to read the payload #58

Closed ghost closed 8 years ago

ghost commented 8 years ago

I have used this module to send a payload with my push notification. I get the pushEvent object at my service worker and in there I find that the data attribute isn't null anymore, so some payload is actually send.

However, my issue is that I do not know how to read the message from the payload. I have tried using JSON.stringify the data attribute but it returns "{}"

webpush used from the server

    webpush.setGCMAPIKey('AIzaSyB71PDpHDx_zNqtMzidfzSp7CqCKV0Y8');
    webpush.sendWebPush('My title', subscription);

service worker file

self.addEventListener('push', function(event) {
  console.log('Push message', event);
  data = {}
  if (event.data) {
    console.log('rawdata', event.data);
    //console.log('data', event.data.json());
    //data = event.data.json();
    data = event.data
    dataString = JSON.stringify(data);
    console.log(dataString);
  }
  title = data.title || 'title'
  body = data.body || 'decription'

  event.waitUntil(
    self.registration.showNotification(title, {
     body: body,
     icon: '../images/icons/icon-192x192.png',
     tag: 'my-tag'
   }));
});

google Chrome developer console:

screen shot 2016-07-20 at 20 12 07
samthor commented 8 years ago

Please check out PushMessageData on MDN. It explains how the .text(), .json() etc methods work on the event.data property, which is of that type.