[英]Why is my Service Worker's push event data/payload null?
我已经多次尝试在Chrome中使用桌面通知,但我没有找到单一的文档来源,其中包含逐步过程以使桌面通知正常工作。 我遇到的每种资源都是过时的或与其他资源不一致。
我面临的问题是:一旦服务工作者收到push
事件,
self.addEventListener('push', function (event) {
console.log(event);
event.waitUntil(
self.registration.showNotification(
event.data.title,
{
body: event.data.body,
icon: event.data.icon,
tag: event.data.tag
}));
});
event.data
为null。 我希望它有一个我在POST请求中作为JSON发送的数据,如下所示:
POST https://fcm.googleapis.com/fcm/send HTTP/1.1
Content-Type: application/json
Authorization: key=<FCM Server Key here>
{
"data": {
"title": "Foo",
"body": "Bar"
},
"to": "<recipient ID here>"
}
奇怪的是注册脚本获得了一个“订阅端点”,看起来像https://android.googleapis.com/gcm/<recipient ID here>
,但我无法通过POST,除非我按照其他示例进行操作web表示将收件人ID作为我发送的JSON中的to
字段。
在我遇到的所有示例中,有多个URL正在进行POST调用:
https://fcm.googleapis.com/fcm/send
https://android.googleapis.com/gcm/send
https://gcm-http.googleapis.com/gcm/send
我已经尝试了所有三个,每次尝试都在API地址的末尾有收件人(例如https://fcm.googleapis.com/fcm/send/<recipient ID here>
,或者在JSON正文中。我的目标是从我发送到self.registration.showNotification(
服务工作者的方法)的数据中获取Foo和Bar 。
为什么event.data
null? 任何人都可以从头到尾指出一个完整的指南,支持FCM而不是GCM吗? 任何帮助,将不胜感激。
您可能需要查看文档中的以下语句,
当前在Chrome中实施Push API的一个缺点是您无法使用推送消息发送任何数据。 不,没什么。 这样做的原因是,在将来的实现中,有效载荷数据必须在服务器上发送到推送消息传递端点之前进行加密。 这样,端点,无论是什么推送提供者,都将无法轻松查看推送消息的内容。 这还可以防止其他漏洞,例如HTTPS证书验证不当以及服务器和推送提供程序之间的中间人攻击。 但是,此加密尚不支持,因此在此期间您需要执行提取以获取填充通知所需的信息。
进一步阅读,您可能希望尝试使用fetch()
从API获取数据,将响应转换为对象并使用它来填充通知。 在这个相关的SO帖子中也使用了同样的方法。
除此之外,您可能还想检查线程中@Indici Indici的响应,其中他说push事件不包含数据值; 相反,它包含不同的事件,其中包含信息。 以下是作为可能的解决方法提供的示例代码,用于在“push”事件中接收Firebase服务工作者的通知:
self.addEventListener('push', function(event) {
if (event.data) {
const dataText = event.data.text();
notificationTitle = 'Custom Notification';
notificationOptions.body = 'Message: ' + `${dataText}`;
var title = event.data.notification.title;
var message = event.data.notification.message;
var icon = event.data.notification.icon;
var notificationTag = event.data.notification.tag;
}
}
对于接收数据需要:
self.addEventListener('push', function(event) {
var jsonData = JSON.parse(event.data.text());
// jsonData -> here is you data
const options = {
body: 'set you body',
icon: 'img/apple-icon-120x120.png',
badge: 'img/apple-icon-120x120.png'
};
event.waitUntil(self.registration.showNotification(jsonData.data.title, options));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.