![](/img/trans.png)
[英]active serviceWorker is not sending message to waiting serviceWorker
[英]Fcm serviceworker receive message in background but code not executed
var config = {
messagingSenderId: "18????????2"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
$.ajax({
type: "POST",
dataType: "json",
data: { notificationID: payload.data.notificationID },
url: "https://myapi/somerestservice",
success: function (data) {
console.log("remove notification status : " + data.Status + " - Message : " + data.Message);
}
});
const notificationTitle = payload.notification.title;
const notificationOptions = {
body:payload.notification.body,
};
return self.registration.showNotification(notificationTitle, notificationOptions);
我在后台收到消息,没有任何错误,并且消息完美显示在浏览器中
我的问题是我需要execute
一些代码以从db
删除数据,但是在收到消息时不会触发在setBackgroundMessageHandler
添加的任何代码,而在后台收到消息时会触发任何事件(在前台,我使用onMessage
,其工作原理很好)
如果在发送HTTP / XMPP请求时(例如从后端)在消息上设置了notification
键,则不会调用在setBackgroundMessageHandler
注册的消息处理程序。 Firebase将为您处理消息并按原样显示。
如果您需要在后台运行应用程序时收到消息时执行某些操作,则可以使用消息上的data
键; 如果省略了notification
键,则将调用在setBackgroundMessageHandler
注册的处理程序,您可以处理有效负载并自定义通知:
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Do you AJAX request here.
// Customize and show your notification
const notificationTitle = payload.data.title,
const notificationOptions = {
body: payload.data.body,
icon: payload.data.icon
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
注意:除了自己显示通知之外,您还必须手动处理单击和关闭事件。
发送消息:
https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{ "data": {
"title": "Hello",
"body": "How are you?",
"icon": "https://..."
},
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}
官方文档的这部分内容可能会有些混乱,但是可以在以下位置找到有关何时调用两个消息处理程序的一些说明: https : //sentinelstand.com/article/handling-firebase-notification-messages-in-your-网络应用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.