我已经看到很多人问这个问题,我已经尝试了答案,我的有效负载中没有所谓的“通知”。
当页面处于前台时,将完全按预期接收消息。
客户代码:
var config = {
apiKey: "<API_KEY>",
authDomain: "AUTH_DOMAIN",
databaseURL: "DATABASE",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "SENDER_ID"
};
firebase.initializeApp(config);
const messaging = firebase.messaging()
messaging.requestPermission()
.then(() => {
console.log('Permission granted')
return messaging.getToken()
})
.then((token) => {
console.log(token)
})
.catch(() => {
console.log('Permission denied')
})
messaging.onMessage((payload)=>{
console.log("message: ", payload)
// TODO: handle message
})
服务人员代码(与客户端相同的配置)
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('Handling background message ', payload);
return self.registration.showNotification(payload.data.title, {
body: payload.data.body,
});
});
服务器代码:
var express = require('express');
var router = express.Router();
var firebase = require('firebase');
var admin = require('firebase-admin');
var serviceAccount = require('./../../../web-quickstart-e2909-1896918629ac.json')
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: '<DB_URL>'
});
const registrationToken = <REGISTRATION_TOKEN>
var message = {
data: {
body: "Hello world!",
title: "Hi",
// icon: "<ICON_SOURCE>"
},
token: registrationToken
};
const sendMessage = () => {
admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
}
sendMessage()
/* GET home page. */
router.get('/', function(req, res, next) {
sendMessage()
res.json({ title: 'Express' });
});
module.exports = router;
在服务器代码中,我确实获得了一条日志,指出该消息已成功发送,但是客户端未收到任何消息,日志insetBackgroundMessageHandler从未被记录。