javascript - Firebase 网络推送通知发送成功但客户端未收到
问题描述
我正在使用 Firebase Web 推送通知 API 并发送带有我想在客户端使用 Postman 和/或从 Firebase 通知编写器显示的消息的帖子请求,消息已成功发送但未收到,如何我可以解决这个问题吗?
这是我得到的回应
{
"multicast_id": 6360733777037549929,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1592759038463623%cc9b4facf9fd7ecd"
}
]
}
我正在使用 Firebase 托管,并包含整个 Firebase Javascript SDK,尽管我已经尝试过仅包含 firebase-messaging SDK。
<body>
<h1>Some Firebase app</h1>
<script src="/__/firebase/7.15.3/firebase.js"></script>
<script src="/__/firebase/init.js"></script>
<script type="text/javascript">
const messaging = firebase.messaging();
messaging.requestPermission()
.then(()=>{
console.log('Permission Granted');
return messaging.getToken()
})
.then((token)=>{
console.log(token);
})
.catch((err)=>{
console.log(err);
})
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
});
</script>
</body>
使用我得到的令牌,并使用我的服务器密钥,我发送以下请求
Method: POST
URL: https://fcm.googleapis.com/fcm/send
Headers: {
Authorization: "key=myServerKey",
Content-Type: "application/json"
}
Body: {
"to" : "token",
"notification" : {
"body" : "Test message",
"title" : "Test title"
}
}
这就是我在 firebase-messaging-sw.js 文件中处理消息的方式
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-messaging.js');
var firebaseConfig = {
apiKey: "xxxx",
authDomain: "newproject-95acc.firebaseapp.com",
databaseURL: "https://newproject-95acc.firebaseio.com",
projectId: "newproject-95acc",
storageBucket: "newproject-95acc.appspot.com",
messagingSenderId: "xxxx",
appId: "xxxx"
};
firebase.initializeApp(firebaseConfig);
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
});
解决方案
您想在前台(有焦点)还是在后台(服务人员)接收消息?
在后台(服务人员)
你能试试下面的代码吗?
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.15.0/firebase-messaging.js');
var firebaseConfig = {
apiKey: "xxxx",
authDomain: "newproject-95acc.firebaseapp.com",
databaseURL: "https://newproject-95acc.firebaseio.com",
projectId: "newproject-95acc",
storageBucket: "newproject-95acc.appspot.com",
messagingSenderId: "xxxx",
appId: "xxxx"
};
firebase.initializeApp(firebaseConfig);
if (firebase.messaging.isSupported()) {
firebase.messaging();
}
请参阅https://firebase.google.com/docs/cloud-messaging/js/receive
如果您在消息负载中设置通知字段,则不会调用您的 setBackgroundMessageHandler 回调,而是 SDK 会根据您的负载显示通知。
或者,你能试试样品吗?
看:
推荐阅读
- reactjs - Typescript spfx 错误:“只读”类型上不存在属性“新闻”<{}>
- python - 如何在没有操作系统的情况下运行 python
- python - 如何从 txt 文件中的拆分行制作嵌套列表?
- java - Spring Boot 1.5 Tomcat 仍在运行
- php - Symfony 4.3 - 传递给 App\Entity\BlogPost::setTitle() 的参数 1 必须是字符串类型,给定 null
- java - 线程似乎会在一段时间后自杀?
- c - SPOJ 中两个列表的中位数总是错误的
- c++ - 如果玩家向左/向右移动,如何更改/更新屏幕?
- javascript - 如何创建一个没有大 app.js 文件的简单 Vue 项目?
- python - 模板为每个用户 Django 呈现相同的信息