gpt4 book ai didi

javascript - Firebase messages.setBackgroundMessageHandler 未接收消息

转载 作者:行者123 更新时间:2023-12-01 04:06:17 24 4
gpt4 key购买 nike

我正在尝试 Firebase 云消息传递。它非常棒,但我很难让它为我工作。

我面临的问题是服务 worker ,这是我的 firebase-messaging-sw.js :

console.log('Service worker is loaded!');

self.addEventListener('install', function(event) {
console.log('Service Worker is being installed.');
});

self.addEventListener('activate', function(event) {
console.log('Service Worker is being activated.');
});

importScripts('https://www.gstatic.com/firebasejs/3.6.5/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.6.5/firebase-messaging.js');

firebase.initializeApp({
'messagingSenderId': ' ... '
});

var messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload){
console.log('Received background message: ', payload);

return self.registration.showNotification('Title', {'body': 'Body'});
});

当我发送消息(我正在使用 PHP-FCM BTW)时,当页面处于焦点状态时,消息会通过 onMessage( ... ) 在浏览器中按预期接收,但永远不会当页面没有焦点或浏览器关闭时; Service Worker 只是没有收到消息!

“收到后台消息:...”这一行永远不会显示;这意味着消息处理程序根本没有注册!

这是一个示例消息响应:

{
"from": " ... ",
"collapse_key": "do_not_collapse",
"data": {
"id": "111"
},
"priority": "high",
"notification": {
"title": "Hi there",
"body": "Message body",
"badge": "1",
"color": "#ffffff"
}
}

这里可能出现什么问题?这让我发疯。

最佳答案

不,它已注册,但由于您选择构建通知的方式而未被调用。引用FCM文档:

https://firebase.google.com/docs/cloud-messaging/js/receive

"Note: If you set notification fields in your HTTP or XMPP send request, those values take precedence over any values specified in the service worker."

所以,你已经

{
"from": " ... ",
"collapse_key": "do_not_collapse",
"data": {
"id": "111"
},
"priority": "high",
"notification": {
"title": "Hi there",
"body": "Message body",
"badge": "1",
"color": "#ffffff"
}
}

并且这个结构永远不会触发BackgroundMessageHandler。因为以这种方式发送数据,只会覆盖您的变量。如果您想触发它,您需要像这样发送通知:

{
"from": " ... ",
"collapse_key": "do_not_collapse",
"priority": "high",
"data": {
"id": "111",
"notification": {
"title": "Hi there",
"body": "Message body",
"badge": "1",
"color": "#ffffff"
}
},
"to": "topic",
}

关于javascript - Firebase messages.setBackgroundMessageHandler 未接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41805933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com