我正在我们的web应用程序中使用firebase web推送通知。
当应用程序未处于活动状态或未打开时,从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 Request:
{
"to":"ids",
"data":{
"body":"clicktoaction",
"title":"Simplext Notification"
}
}
无论应用程序是在前台还是后台,始终调用事件messaging.onMessage(函数(有效负载)。
我试着将fcm请求从“data”改为“notification”。还是一样的。
我用的是chrome v 70。