Search code examples
javascriptpayloadweb-push

Get value from web push notification payload


I received this payload from a web push notification.

{
  "data": {
    "notification": "{\"icon\":\"\\/static\\/assets\\/notifications\\/loader-100x100.png\",\"vibrate\":[200,100,200,100,200,100,400],\"tag\":\"request\",\"body\":\"12:30\",\"title\":\"HELLO\",\"actions\":[{\"icon\":\"\\/static\\/assets\\/notifications\\/loader-100x100.png\",\"action\":\"https:\\/\\/example.com\\/#done\",\"title\":\"OK\"},{\"icon\":\"\\/static\\/assets\\/notifications\\/loader-100x100.png\",\"action\":\"https:\\/\\/example.com\\/#open\",\"title\":\"Edit\"}]}"
  },
  "collapse_key": "do_not_collapse",
  "from": "1111111"
}

How to get the value of title? I tried this without luck:

var parsed = JSON.parse(payload);
const notificationTitle = parsed["notification"]["title"];

Solution

  • With that object just do

    var parsedNotification = JSON.parse(payload.data.notification);
    var title = parsedNotification.title;
    console.log(title);