13

I am trying to use push notification in a pwa, but it is failing to receive the notification.

On the client side I am receiving the following error

Uncaught SyntaxError: Unexpected token P in JSON at position 0
at Driver.onPush (ngsw-worker.js:1967)
at ngsw-worker.js:1871

I add an image that includes the data that reaches the service worker

As you can see in the previous image, the data field is empty, however when I send it I am adding a text

To test the application I am releasing the notification with the following:

https://web-push-codelab.glitch.me/

I already appreciate any contribution.

Fernando Arbelo
  • 185
  • 2
  • 14
  • It's not empty, it contains an empty object of type `PushMessageData`. I suspect it gets serialized to something like `PushMessageData{}` yielding the error you see. – yeputons Dec 26 '18 at 17:01
  • Thank you very much for the reply, anyway the problem comes on the other hand, if I apply msg.data.text() it shows me the information correctly, unfortunately I can not touch that in the code to use text() instead of json() since it is generated in the folder /dist – Fernando Arbelo Dec 26 '18 at 17:19
  • Do you use some standard library? If so, please provide [MCVE](https://stackoverflow.com/help/mcve) so we can see if there is any misuse. If you use some 3rd-party open source library, please provide [MCVE](https://stackoverflow.com/help/mcve) for the same reason. If you use some closed-source 3rd-party code, I'm not sure how strangers from the Internet can help you. – yeputons Dec 26 '18 at 17:36

2 Answers2

11

If your payload is in any json format, like the one above, the error does not appear, but the notification is not shown in your client and no other error message is shown. You have to use a certain json format. One minimal working payload is:

{ "notification": {"title": "message title", "body": "message body"} }

I haven't found the exact and complete spec for this json, but here (search for "payload") you'll find a more complete example.

Sudarshana Dayananda
  • 5,165
  • 2
  • 23
  • 45
  • Thank you that helped me ! here is the spec i found : [https://notifications.spec.whatwg.org/](https://notifications.spec.whatwg.org/) see '2. Notifications' – youssef Mar 03 '19 at 02:22
2

Make sure you are correctly sending the payload.

Everything is fine except ngsw-worker can't parse the payload.

If you are on windows, try this:

--payload="{\"hello\":\"world\"}"

And not this:

--payload='{"hello":"world"}'

Example (using webpush cli):

web-push send-notification --endpoint="https://fcm.googleapis.com/fcm/send/xxx:xxx" --key="xxxxxxxxxxxxx" --auth="xxxxxxxxxx" --payload="{\"hello\":\"world\"}" --vapid-subject="https://localhost:8000" --vapid-pubkey=xxxxxxxxxx --vapid-pvtkey=xxxxxxxx
dasfdsa
  • 7,102
  • 8
  • 51
  • 93