[英]Web firebase.messaging().onMessage not fired, but background notification perfectly fired
I want to reload or trigger some event in foregrounf if push message is sent with firebase.messaging().onMessage, but it not fired.如果使用 firebase.messaging().onMessage 发送推送消息,我想在前台重新加载或触发某些事件,但它没有被触发。 I'm using firebase.mesaging.sw.js with background notification and it works correctly what is wrong with my code?我正在使用带有后台通知的 firebase.mesaging.sw.js 并且它可以正常工作我的代码有什么问题?
firebase.js firebase.js
const config = {
apiKey: "x",
projectId: "x",
storageBucket: "x",
messagingSenderId: "x"
};
firebase.initializeApp(config);
const msg = firebase.messaging()
msg.requestPermission()
.then(() => {
return msg.getToken()
})
.then((token) => {
})
.catch((err) => {
})
msg.onMessage(function(payload) {
alert("Foreground message fired!")
console.log(payload)
});
firebase.messaging.sw.js firebase.messaging.sw.js
importScripts("https://www.gstatic.com/firebasejs/7.0.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/7.0.0/firebase-messaging.js");
const config = {
apiKey: "x",
projectId: "x",
storageBucket: 'x',
messagingSenderId: "x"
};
firebase.initializeApp(config);
const msg = firebase.messaging()
msg.setBackgroundMessageHandler(function(payload) {
let options = {
body: payload.data.body,
icon: payload.data.icon
}
return self.registration.showNotification(payload.data.title, options);
});
I don't know what is wrong with my code我不知道我的代码有什么问题
Simple solution to this is update your Firebse to latest version.对此的简单解决方案是将您的Firebse更新到最新版本。
Eg.例如。
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js');
Note: Once you have updated your firebase libraries versions then messagingSenderId will not work in your firebase-messaging-sw.js file.注意:一旦您更新了 firebase 库版本,那么 messagesSenderId 将无法在您的 firebase- messaging -sw.js文件中使用。 You have to provide all other params eg.您必须提供所有其他参数,例如。 apiKey, projectId, appId along with messagingSenderId . apiKey、projectId、appId以及messagesSenderId 。
For more details you can refer to this solution有关更多详细信息,您可以参考此解决方案
For anyone else with this problem, I finally solved it by:对于其他有此问题的人,我终于通过以下方式解决了它:
firebaseConfig
array to the SW firebase.initializeApp()
, as the previous answer suggests.如前一个答案所示,将整个firebaseConfig
数组添加到 SW firebase.initializeApp()
。Basically, a total fresh start with updated Firebase SDK seems to fix issues like this.基本上,从更新的 Firebase SDK开始全新的开始似乎可以解决此类问题。
Still had the same issue in 2020. In my case it was like this: 2020 年仍然有同样的问题。就我而言,情况是这样的:
importScripts
for background messages and in your app for foreground messages您需要在importScripts
中为后台消息使用相同的版本,在您的应用程序中为前台消息使用相同的版本firebaseApp.messaging().getToken().then((currentToken) => {
if (currentToken) {
console.log(currentToken)
} else {
// Show permission request.
console.log(
'No Instance ID token available. Request permission to generate one.')
}
/** When app is active */
firebase.messaging().onMessage((payload) => {
console.log(payload)
}, e => {
console.log(e)
})
})
You are missing lots of things and onMessage will only work if firebase is initialized before calling it.你错过了很多东西,只有在调用 firebase 之前初始化它, onMessage 才会起作用。 Please follow this.请遵循此。 I have done it like this and it is working.我已经这样做了,它正在工作。
initialize firebase and get the token初始化 firebase 并获取令牌
export class BrowserFcmProvider {
export const FIREBASE_CONFIG = {
apiKey: "****",
authDomain: "****",
databaseURL: "****",
projectId: "****",
storageBucket: "****",
messagingSenderId: "****",
appId: "****"
}
firebase.initializeApp(FIREBASE_CONFIG);
async webGetToken() {
try {
const messaging = firebase.messaging();
await messaging.requestPermission();
const token = await messaging.getToken();
let uuidTemp = new DeviceUUID().get();
return this.saveTokenToFireStoreFromWeb(token, uuidTemp)
} catch (e) {
console.log(e);
}
}
saveTokenToFireStoreFromWeb(token, uuid) {
try {
const docData = {
token: token,
device_type: 'web',
uuid: uuid
}
const devicesRef = this.db.collection('devices')
return devicesRef.doc(uuid).set(docData);
} catch (e) {
console.log(e, 'saveTokenError');
}
}
showMessage() {
try {
const messaging = firebase.messaging();
messaging.onMessage((payload) => {
console.log(payload);
})
} catch (e) {
console.log(e)
}
}
}
And calling the method while app loads like this并在应用程序加载时调用该方法
async configureFirebaseForBrowser(res) {
await this.bfcm.webGetToken();
this.bfcm.showMessage();
}
Firebase function and payload type Firebase function 和有效载荷类型
const payloadWeb = {
title: title,
body: body,
data: {
title: title,
body: body
},
tokens: uniqueDevicesTokenArrayWeb,
}
const responseWeb = await admin.messaging().sendMulticast(payloadWeb);
console.log(responseWeb.successCount + ' notifications has been sent to Web successfully');
I have used async and await as we need to manage firebase/firestore operations asynchronously.我使用了 async 和 await 因为我们需要异步管理 firebase/firestore 操作。
fcm does not work in Incognito mode and safari browser fcm 在隐身模式和 safari 浏览器下不起作用
Same issue i was faced.我面临同样的问题。 In my case firebase version in "package.json" and "firebase-messaging-sw.js" importScripts version was different.就我而言, “package.json”和“firebase-messaging-sw.js” importScripts 版本中的 firebase 版本不同。 After set same version in "firebase-messaging-sw.js" importScripts which was in "package.json" , my issue is resolved.在"package.json"中的 "firebase -messaging-sw.js" importScripts 中设置相同版本后,我的问题得到解决。
Before change变更前
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.8.0/firebase-messaging.js');
After change改变后
**"package.json"**
"firebase": "^8.2.1",
**"firebase-messaging-sw.js"**
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.2.1/firebase-messaging.js');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.