ReferenceError: self is not defined at isSupported - Next.js 在获取消息对象时出错

问题描述

我正在尝试按照 Firebase Cloud Messaging 的 official docs 将 Firebase Cloud Messaging 添加到我的 Next.js 应用中。

但我在 ReferenceError: self is not defined at isSupported 处收到 firebase.messaging() 错误

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

functions.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();

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...