Open custom url when clicking on web push notification

I am implementing Webpush ruby pearls to send push notifications to users of my website.

Server Code:

  Webpush.payload_send({
      message: notification.message,
      url: notification.url,  # I can't figure out how to access this key
      id: notification.id,    # or this key from the service worker
      endpoint: endpoint,
      p256dh: p256dh_key,
      vapid: vapid_keys,
      ttl: 24 * 60 * 60,
      auth: auth_key,
    })

I have a working service configured on the client side to show the notification and make it available.

self.addEventListener("push", function (event) {
  var title = (event.data && event.data.text()) || "New Message";

  event.waitUntil(
    self.registration.showNotification(title, {
      body: "New push notification",
      icon: "/images/logo@2x.png",
      tag:  "push-notification-tag",
      data: {
        url: event.data.url, // This is returning null
        id: event.data.id // And this is returning null
      }
    })
  )
});

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  event.waitUntil(
    clients.openWindow(event.data.url + "?notification_id=" + event.data.id)
  );
})

Everything works fine, except that the user keys ( url, id) that I am viewing are not accessible from the working one.

Does anyone know how to pass user data through the gem of WebPush?

+6
source share
2 answers

Webpush ( ) , , JSON.stringify() JSON.parse().

:

Webpush.payload_send({
  message:JSON.stringify({
    message: notification.message,
    url: notification.url,
    id: notification.id,
  }),
  endpoint: endpoint,
  p256dh: p256dh_key,
  vapid: vapid_keys,
  ttl: 24 * 60 * 60,
  auth: auth_key,
})

:

 event.waitUntil(
   self.registration.showNotification(title, {
   body: "New push notification",
   icon: "/images/logo@2x.png",
   tag:  "push-notification-tag",
   data: {
     url: JSON.parse(event.message).url
   }
})
+4

event.notification ( > ). , alertclick, :)

self.addEventListener('notificationclick', function(event) {
  event.notification.close();
  event.waitUntil(
    clients.openWindow(event.notification.data.url + "?notification_id=" + event.notification.data.id)
  );
})
+6

Source: https://habr.com/ru/post/1017274/


All Articles