我正在尝试在Next Js项目中设置Firebase云消息,以添加以下文件
一个/public/firebase-messaging-sw.js
importScripts("https://www.gstatic.com/firebasejs/9.20.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/9.20.0/firebase-messaging.js");
const firebaseConfig = {
apiKey: "A.............KU0",
authDomain: "ad......f.firebaseapp.com",
projectId: "a.......f",
storageBucket: "ad......m",
messagingSenderId: "6.....0",
appId: "1:63....331",
measurementId: "G........Z"
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
console.log(
"[firebase-messaging-sw.js] Received background message ",
payload
);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: payload.notification.image,
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
/helper/firebase.js
中的第二个:
import { initializeApp } from "firebase/app";
import { getMessaging } from "firebase/messaging";
const firebaseConfig = {
apiKey: "A.............KU0",
authDomain: "ad......f.firebaseapp.com",
projectId: "a.......f",
storageBucket: "ad......m",
messagingSenderId: "6.....0",
appId: "1:63....331",
measurementId: "G........Z"
};
export const app = initializeApp(firebaseConfig);
export let messaging
if (process.browser) {
// because I'm getting error "Navigator not defined"
messaging = getMessaging(app)
};
export const VAPID_KEY = "BGP.....................A"
/helper/pushNotification.js
import { getToken } from "firebase/messaging";
import { VAPID_KEY, messaging } from "./firebase";
export const requestNotificationPermission = async () => {
if ('Notification' in window) {
const permission = await Notification.requestPermission()
if (permission === 'granted') {
console.log('Notification permission granted.');
const token = await getToken(messaging, { vapidKey: VAPID_KEY })
console.log('+++ token', token);
} else if (permission === "denied") {
alert('permission === "denied"')
}
}
}
/navbar.js
useEffect(() => {
requestNotificationPermission()
}, [])
我得到这个错误
捕获DOMException:无法在“WorkerGlobalScope”上执行“importScripts”:无法加载位于“https://www.gstatic.com/firebasejs/9.20.0/firebase-app.js”的脚本。
网址:http://localhost:3006/firebase-messaging-sw.js:1:1(匿名)@firebase-messaging-sw. js:1
有关于如何解决这个问题的建议和文件来正确实施的建议吗?
1条答案
按热度按时间smdnsysy1#
在
firebase.js
文件中使用此代码