2017-05-15 77 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