单击网络推送通知时打开自定义 url

新手上路,请多包涵

我正在实施 Webpush ruby gem 以向我网站的用户发送推送通知。

服务器代码:

   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,
    })

我在客户端设置了一个服务人员来显示通知并使其可点击。

 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)
  );
})

一切正常,除了我正在传递的自定义键( urlid )无法从服务工作者内部访问。

有谁知道如何通过 WebPush gem 传递自定义数据?

原文由 BananaNeil 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 349
2 个回答

Webpush (with a payload) documentation 看来,您应该使用 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
   }
})

原文由 Jonas Wilms 发布,翻译遵循 CC BY-SA 3.0 许可协议

自定义数据来自 event.notification 对象,而不是直接来自 事件(在 notificationclick 中)。所以如果你想在 notificationclick 函数中获取自定义数据变量,那么你应该这样做:)

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

原文由 munjal 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题