Firebase onMessage 未被触发



我在使用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);
});

索引.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获取通知的正确方法是什么?还是我做错了什么?

首先,我的邮递员要求不是绝对正确的。Firebase 请求有两种类型,一种仅适用于活动的浏览器标签页,另一种可以在后台运行。我使用了第一个,这就是为什么我看不到 onMessage 没有触发。

邮递员请求应该是

https://fcm.googleapis.com/fcm/send
{
"data": {
"title": "test",
"body": "test",
"click_action": "http://localhost:8001/"
},
"to": "token"
}

辅助,在订阅令牌并将其发送到服务器之前,必须调用messaging.usePublicVapidKey()

最后一个,messaging.onMessage也必须在向服务器发送令牌之前

相关内容

  • 没有找到相关文章

最新更新