我在我们的网络应用程序中使用 Firebase 网络推送通知。
当应用程序未激活或打开时,从 FCM 发送的消息永远不会显示。没有生成错误。
前端代码:
<script src="https://www.gstatic.com/firebasejs/5.6.0/firebase.js"></script>
<script>
MsgElem = document.getElementById("msg")
TokenElem = document.getElementById("token")
NotisElem = document.getElementById("notis")
ErrElem = document.getElementById("err")
// Initialize Firebase
// TODO: Replace with your project's customized code snippet
var config = {
apiKey: "<apikey>",
authDomain: "<app>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
storageBucket: "<app>.appspot.com",
messagingSenderId: "<id>",
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = "Notification permission granted."
console.log("Notification permission granted.");
// get the token in the form of promise
return messaging.getToken()
})
.then(function(token) {
TokenElem.innerHTML = "token is : " + token
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
console.log("Unable to get permission to notify.", err);
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
NotisElem.innerHTML = NotisElem.innerHTML + JSON.stringify(payload)
});
</script>
firebase-messaging-sw.js
importScripts ('https://www.gstatic.com/firebasejs/5.6.0/firebase-app.js');
importScripts ('https://www.gstatic.com/firebasejs/5.6.0/firebase-messaging.js');
firebase.initializeApp ({'messagingSenderId': 'id'});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler (function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
const data = payload.data;
const notificationTitle = data.title;
const notificationOptions = {
body: data.body
};
return self.registration.showNotification (notificationTitle, notificationOptions);
});
FCM 请求:
{
"to":"ids",
"data":{
"body":"clicktoaction",
"title":"Simplext Notification"
}
}
无论应用程序是在前台还是在后台,事件 messages.onMessage(function(payload) 总是被调用。
我尝试将 FCM 请求从“数据”更改为“通知”。还是一样。
我使用的是 Chrome v 70。
最佳答案
我最终发现 Firebase 客户端应用程序应该位于 https 下,serviceworker 才能工作。
关于javascript - Firebase Web Push 后台消息永远不会显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53591645/