2017-05-15 80 views
6

我正在实施Webpush ruby gem向我的网站的用户发送推送通知。点击网页推送通知时打开自定义网址

Server代码:

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/[email protected]", 
     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宝石传递自定义数据?

+0

即时通讯不是专家,但我会这样做:message:JSON.stringify(notification)on服务器和客户端上的JSON.parse ... –

+0

@Jonasw - 我结束了你的解决方案。如果你把它写成答案,我会接受它。谢谢您的帮助。 – BananaNeil

回答

4

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/[email protected]", 
    tag: "push-notification-tag", 
    data: { 
    url: JSON.parse(event.message).url 
    } 
}) 
5

自定义数据来自于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) 
); 
}) 
+1

问题在于接收来自推送事件的数据,而不是来自click事件。但是你是对的,那是我最终需要修复的另一个bug。 – BananaNeil