firebase-cloud-messaging - Firebase 消息,未调用 onMessage
问题描述
这就是我调用发送消息的方式:
sendMessage() {
var key = 'VERY LONG KEY -dffdADFDFD-vdfDafd';
var to = 'VERY LONG KEY -ADEWerew-vdfDafd';
var notification = {
'title': 'Portugal vs. Denmark',
'body': '5 to 1'
};
fetch('https://fcm.googleapis.com/fcm/send', {
'method': 'POST',
'headers': {
'Authorization': 'key=' + key,
'Content-Type': 'application/json',
},
'body': JSON.stringify({
'to': to,
'notification': notification,
'data': {
'message': 'example'
}
})
}).then(function (response) {
console.log(response);
response.json().then(function (result) {
console.log(result);
})
}).catch(function (error) {
console.error(error);
})
}
这是我的 onMessage:
messaging.onMessage(function (payload) {
console.log("Message received. ", payload);
});
但它没有进入上面的代码块。目前我正在测试应用程序何时打开并具有焦点。
解决方案
服务工作者也用于 onMessage:
/**
* Check out https://googlechromelabs.github.io/sw-toolbox/ for
* more info on how to use sw-toolbox to custom configure your service worker.
*/
'use strict';
//importScripts('./build/sw-toolbox.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
firebase.initializeApp({
'messagingSenderId': '147703423097'
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
推荐阅读
- javascript - 反应 .map 不渲染
- macos - Mac 命令行工具 11.4 不再有 svn
- javascript - typescript - 具有静态方法的抽象类
- c# - 仅接收部分 udp 消息
- python - 在 python 中使用 print 时删除指定的字符
- python - 尝试使用 OnehotEncoder 创建虚拟变量
- java - Android socket io事件和Channel
- ios - Swift 5 的 UnsafeMutablePointer 警告
- sql - 如何根据特定列选择重复项
- ibm-doors - 存储在 DXL 脚本填充的属性中的意外结果