javascript - messages.setBackgroundMessageHandler 未在网络中接收消息
问题描述
我正在 web 应用程序中实现 firebase 通知。当网页未激活时,我无法接收后台通知。
到目前为止我所做的是:
manifest.json
使用代码在根目录中 创建:{ "gcm_sender_id": "103953800507" }
firebase-messaging-sw.js
使用以下代码在根目录中创建文件:
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
firebase.initializeApp({
'messagingSenderId': '11111'
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
//sometime receive notification in this
debugger;
//some code here to receive notification..
return self.registration.showNotification(title,
notificationOptions);
});
- 在
Home/Index
页面中输入以下代码以获取权限和令牌
firebase.initializeApp({
'messagingSenderId': '11111'
});
const messaging = firebase.messaging();
messaging.requestPermission().then(function() {
console.log('Notification permission granted.');
messaging.getToken().then(function(currentToken) {
if (currentToken) {
console.log(currentToken);
sendTokenToServer(currentToken); //save in database
}
}).catch(function(err) {
console.log('An error occurred while retrieving token. ', err);
});
}).catch(function(err) {
console.log('Unable to get permission to notify.', err);
});
messaging.onTokenRefresh(function() {
messaging.getToken().then(function(refreshedToken) {
sendTokenToServer(refreshedToken);
}).catch(function(err) {
});
});
messaging.onMessage(function (payload) {
//receive notification here when this page is active. working fine
});
如何在messaging.setBackgroundMessageHandler 中接收通知?
解决方案
上面提到的代码很好。问题出在app focus
. 假设我有页面 p1、p2 和 p3。
p1 具有获取通知权限、获取令牌和接收前台通知的代码。我期待 p2 和 p3 页上的背景通知。
但是只有当这两个页面messaging.setBackgroundMessageHandler
不在浏览器的当前焦点选项卡中时,它们才会收到通知。