【发布时间】:2020-02-07 12:28:19
【问题描述】:
我在使用 Firebase 推送通知时遇到问题。 onMessage 事件未触发
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/7.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.1/firebase-messaging.js');
firebase.initializeApp({
apiKey: "some_data",
authDomain: "some_data",
databaseURL: "some_data",
projectId: "some_data",
storageBucket: "some_data",
messagingSenderId: "some_data",
appId: "some_data",
measurementId: "some_data"
});
var messaging = firebase.messaging();
messaging.onMessage(function(payload) {
console.log('Message received. ', payload);
});
index.html
<script src="https://www.gstatic.com/firebasejs/7.8.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.8.1/firebase-messaging.js"></script>
<script>
firebase.initializeApp({
apiKey: "some_data",
authDomain: "some_data",
databaseURL: "some_data",
projectId: "some_data",
storageBucket: "some_data",
messagingSenderId: "some_data",
appId: "some_data",
measurementId: "some_data"
});
if ('Notification' in window) {
navigator.serviceWorker.register("js/firebase-messaging-sw.js")
.then((registration) => {
var messaging = firebase.messaging();
messaging.useServiceWorker(registration);
console.log(messaging);
if (Notification.permission === 'granted') {
subscribe(messaging);
messaging.onMessage(function(payload) {
console.log('Message received. ', payload);
});
}
$('#subscribe').on('click', function () {
subscribe(messaging);
});
});
}
function subscribe(messaging) {
messaging.requestPermission()
.then(function () {
messaging.getToken()
.then(function (currentToken) {
console.log(currentToken);
if (currentToken) {
sendTokenToServer(currentToken);
}
})
.catch(function (err) {
setTokenSentToServer(false);
});
})
.catch(function (err) {
console.warn('not granted', err);
});
}
function sendTokenToServer(currentToken) {
if (!isTokenSentToServer(currentToken)) {
console.log('Отправка токена на сервер...');
var url = '';
$.post(url, {
token: currentToken
});
setTokenSentToServer(currentToken);
}
}
function isTokenSentToServer(currentToken) {
return window.localStorage.getItem('sentFirebaseMessagingToken') == currentToken;
}
function setTokenSentToServer(currentToken) {
window.localStorage.setItem(
'sentFirebaseMessagingToken',
currentToken ? currentToken : ''
);
}
</script>
我能够获取令牌并将其发送到服务器。但是当我发送 邮递员的请求
https://fcm.googleapis.com/fcm/send
{
"notification": {
"title": "test",
"body": "test",
"click_action": "http://localhost:8001/"
},
"to": "token"
}
我在网页上什么都看不到,没有消息(邮递员的响应有 200 状态)
从 Firebase 获取通知的正确方法是什么?还是我做错了什么?
【问题讨论】:
-
您是否发送了
POST请求并验证您发送的数据是否正确? -
@Edric - 是的,我发送了 post 请求,我得到了有效的回复
{ "multicast_id": 551265091536786344, "success": 1, "failure": 0, "canonical_ids": 0, "results": [ { "message_id": "0:1581072871865893%cc9b4facf9fd7ecd" } ] }
标签: javascript firebase firebase-cloud-messaging