FCM错误:服务消息传递不可用


import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { getMessaging } from "firebase/messaging";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyA0dAgRPZLlgULgnOp2MH_3xtVbWPs03Cg",
authDomain: "u-63f99.firebaseapp.com",
projectId: "u-63f99",
storageBucket: "u-63f99.appspot.com",
messagingSenderId: "884933400988",
appId: "1:884933400988:web:0b7e0e37b0f23da236d059",
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const fireStore = getFirestore(app);
const messaging = getMessaging(app);
export { auth, fireStore, messaging };

我得到这个错误,我不知道为什么消息服务丢失,而我安装了firebase SDK

当我在Next.js (localhost)中得到这个问题时,我在互联网上搜索,最后我找到了这个解决方案。主要问题是在firestore.js中调用getMessaging,而不是

useEffect(() => {
if (
"Notification" in window &&
"serviceWorker" in navigator &&
"PushManager" in window
) {
const messaging = getMessaging(app);
requestNotificationPermission();
const getFCMToken = async () => {
try {
const token = await getToken(messaging, {
vapidKey:
"Your_KEY",
});
if (token) {
console.log("FCM token:", token);
} else {
console.log("No FCM token received.");
}
} catch (error) {
console.error("Error getting FCM token:", error);
}
};
getFCMToken();
} else {
console.log("FCM not supported");
}
}, []);

这段JavaScript代码被封装在React的useEffect钩子中,检查浏览器是否支持通过Service Workers和push Manager发送通知和推送通知。如果支持,它将初始化消息传递服务,请求通知权限,并获得用于发送推送通知的Firebase Cloud messaging (FCM)令牌。如果不支持,则记录不支持FCM。

PS: Brave浏览器需要在Brave://settings/privacy中启用google推送消息服务

你的问题可能是因为你在本地主机(http)上测试了这个

如果你查看控制台日志,你可能会注意到错误旁边有这样的内容:code: 'messaging/unsupported-browser'

和云消息只支持HTTPS连接,所以你必须让你的本地主机在HTTPS上运行,以使它工作:)

最新更新