You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Firebase Analytics与Firestore时遭遇window未定义ReferenceError求助

解决Firebase Analytics的"window is not defined"错误

问题原因

Firebase Analytics是专为浏览器环境开发的服务,依赖浏览器提供的window对象。你当前的代码运行在Node.js(非浏览器)环境中,无法访问window,因此抛出该错误。同时你的代码还存在一个变量名错误:getDocs(citiesCol)中的citiesCol未定义,应该替换为前面声明的Account。

修复方案

方案1:仅在浏览器环境初始化Analytics

如果你的代码需要同时兼容浏览器和Node.js环境,添加环境判断逻辑,仅在浏览器中初始化Analytics:

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics, isSupported } from "firebase/analytics";
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';

// Your web app's Firebase configuration
const firebaseConfig = {
  // 你的配置内容
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

// 仅在浏览器环境且支持Analytics时初始化
let analytics;
if (typeof window !== 'undefined') {
  isSupported().then((supported) => {
    if (supported) {
      analytics = getAnalytics(app);
    }
  });
}

const db = getFirestore(app);

async function getAccount(db) {
    const accountCol = collection(db, 'Account');
    const accountSnapshot = await getDocs(accountCol); // 修复变量名错误
    const accountList = accountSnapshot.docs.map(doc => doc.data());
    return accountList;
}

// 正确处理异步函数的返回值
getAccount(db)
  .then(accountList => console.log(accountList))
  .catch(error => console.error('获取数据失败:', error));

方案2:纯Node.js环境移除Analytics代码

如果你的代码仅在Node.js环境运行(比如后端脚本),直接删除所有Analytics相关的导入和初始化代码即可:

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';

// Your web app's Firebase configuration
const firebaseConfig = {
  // 你的配置内容
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

async function getAccount(db) {
    const accountCol = collection(db, 'Account');
    const accountSnapshot = await getDocs(accountCol); // 修复变量名错误
    const accountList = accountSnapshot.docs.map(doc => doc.data());
    return accountList;
}

// 正确处理异步函数的返回值
getAccount(db)
  .then(accountList => console.log(accountList))
  .catch(error => console.error('获取数据失败:', error));

额外说明

  • 异步函数getAccount返回的是Promise对象,直接console.log(getAccount(db))只会打印Promise,必须用then/catch或async/await处理结果
  • isSupported()函数用于检测当前浏览器是否支持Analytics的所有功能,避免在不兼容的浏览器中初始化失败

内容的提问来源于stack exchange,提问作者Peeradon Panpakdeewong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 18:47:46