[英]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.