首页 > 解决方案 > ReferenceError: self is not defined at isSupported - Next.js 在获取消息对象时出错

问题描述

我正在尝试按照 Firebase Cloud Messaging 的官方文档将 Firebase Cloud Messaging 添加到我的 Next.js 应用程序中。

但我ReferenceError: self is not defined at isSupportedfirebase.messaging()

基本上我有一个firebaseClient.js文件,我想将messaging对象导出到我的functions.js文件中,但是当我从组件中触发此函数时出现错误。

函数.js

import { messaging } from "./firebaseClient";

export const enableNotification = async () => {
  try {
    if ((await localforage.getItem("fcm_token")) !== null) {
      return false;
    }
    await Notification.requestPermission();
    const token = await messaging.getToken();
    localforage.setItem("fcm_token", token);
    console.log("fcm_token", token);
  } catch (error) {
    console.log(error);
    throw error;
  }
};

firebaseClient.js

import firebase from "firebase/app";
import "firebase/firestore";
import "firebase/messaging";

const clientCredentials = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
};

if (!firebase.apps.length) {
  firebase.initializeApp(clientCredentials);
}
export default firebase;

//for firestore
export const db = firebase.firestore();

//fore firebase cloud messaging
export const messaging = firebase.messaging();

还有一件奇怪的事情,我在服务器控制台而不是客户端上获取控制台日志,因为该文件应该在客户端上运行。

标签: firebasegoogle-cloud-firestorefirebase-cloud-messagingnext.jsgoogle-cloud-messaging

解决方案


推荐阅读