我正在实施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/[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)
);
})
一切正常,除了我通过的自定义键(url
,id
)无法从服务工作者中访问。
有谁知道如何通过WebPush gem传递自定义数据?
从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
}
})
自定义数据在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)
);
})
在node_modules/@angular/service-worker/ngsw-worker.js内的Angular项目中添加它
this.scope.addEventListener('notificationclick', (event) => {
console.log('[Service Worker] Notification click Received. event:%s', event);
event.notification.close();
if (clients.openWindow && event.notification.data.url) {
event.waitUntil(clients.openWindow(event.notification.data.url));
}
});
您可以输入上面的代码,您可以在文件中找到此行
this.scope.addEventListener('notificationclick', (event) => ..
而且你必须再次建立dist以使其工作。在后端,您需要使用以下格式:
{"notification":{"body":"This is a message.","title":"PUSH MESSAGE","vibrate":[300,100,400,100,400,100,400],"icon":"https://upload.wikimedia.org/wikipedia/en/thumb/3/34/AlthepalHappyface.svg/256px-AlthepalHappyface.svg.png","tag":"push demo","requireInteraction":true,"renotify":true,"data":{"url":"https://maps.google.com"}}}
在网址中,您可以输入您的网址,点击通知您的推送通知将打开指定的链接并将其集中在浏览器中