bounty将在4天后过期。回答此问题可获得+150声望奖励。Daniel_Kamel希望引起更多人关注此问题。
在我的Nextjs
项目中,我尝试使用firebase messaging
(我的firebase版本是8.10.0)实现推送通知,在我的公共文件夹中创建了firebase-messaging-sw.js
文件:
importScripts(
"https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"
);
importScripts(
"https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js"
);
const firebaseConfig = {
apiKey: "***",
authDomain: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***"
};
firebase.initializeApp(firebaseConfig)
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: null,
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
现在我创建了一个[utility]文件(命名为Firebase.js
),我将在其中实现像request token函数这样的辅助函数。
下面是该文件的代码片段:
import firebase from "firebase/app";
import "firebase/messaging";
const firebaseConfig = {
apiKey: "***",
authDomain: "***",
projectId: "***",
storageBucket: "***",
messagingSenderId: "***",
appId: "***",
measurementId: "***"
};
!firebase.apps.length && firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
export const requestForToken = () => {
// func that generates and returns a FCM token
};
export const onMessageListener = async () =>
new Promise((resolve) => {
messaging.onMessage((payload) => {
resolve(payload);
}
);
});
现在,为了使用这些函数,我创建了另一个文件Notification.js
:
import React, { useState, useEffect } from "react";
import { toast } from "react-toastify";
import { requestForToken, onMessageListener } from "./Firebase";
const Notification = () => {
const [notification, setNotification] = useState({ title: "", body: "" });
useEffect(() => {
requestForToken();
}, []);
const ToastDisplay = () => {
return (
<>
<b>{notification?.title} </b>
<p>{notification?.body}</p>
</>
);
};
const notify = () => toast(<ToastDisplay />);
useEffect(() => {
notification?.title && notify();
}, [notification]);
onMessageListener()
.then((payload) => {
setNotification({
title: payload?.notification?.title,
body: payload?.notification?.body,
});
})
.catch((err) => console.log("failed: ", err));
return <></>;
};
export default Notification;
我在_app.js
中导入了Notification.js
,当我运行我的应用时,我得到了以下错误:
我不明白为什么,更重要的是,我不明白如何解决这个问题。
1条答案
按热度按时间6kkfgxo01#
试试这个:
还可以查看一下firebase docs
编辑:
再看一下here,它展示了如何将消息接收到客户端。
希望我能帮到你:)