我一直在尝试在前端自定义通知消息,即如果未在通知中设置字段发送,我正在尝试添加它。
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-messaging.js');
var config = {
apiKey: "x",
authDomain: "y",
databaseURL: "z",
projectId: "a",
storageBucket: "b",
messagingSenderId: "1"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
console.log('came here');
console.log(messaging.bgMessageHandler);
console.log(messaging.setBackgroundMessageHandler,'dsafdsadasfd')
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
var notificationTitle = 'Background Message Title';
var notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
console.log(notificationOptions)
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
console.log(messaging.bgMessageHandler);
在执行上面的代码时,即使我收到通知,我也没有得到[firebase-messaging-sw.js] Received background message ', payload
的控制台。
为什么setBackgroundMessageHandler
无效?
答案 0 :(得分:2)
当应用程序在后台运行时,您在json请求中看起来像是发送消息的问题。
注意:如果在HTTP或XMPP发送请求中设置通知字段,则这些值优先于服务工作者中指定的任何值。
https://firebase.google.com/docs/cloud-messaging/js/topic-messaging
因此,以下格式不会调用后台处理程序:
{
to: "e-DLMv........._DiL",
notification: {
body: "Backgound-Message"
}
}

在数据中发送包含通知的消息(它将起作用):
{
to: "e-DLMv........._DiL",
data: {
notification: {
body: "Backgound-Message"
}
}
}