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

使用Firebase JS 9版本初始化报错:GoogleAuthProvider未定义如何解决

问题核心原因

  1. Firebase 9 采用ES模块化规范,你在带type="module"属性的firebase.js里导入的GoogleAuthProvider仅在当前模块作用域生效,普通脚本custom.js无法直接跨脚本访问,同时你也没有导出需要复用的Firebase实例。
  2. custom.js中缺少GoogleAuthProvider、signInWithPopup的导入,也没有初始化Auth实例,内联的onclick事件也无法直接访问模块内的函数。
  3. 你原代码中credentialFromResult的调用方式错误,该方法是GoogleAuthProvider的静态方法,不是实例方法。

修复步骤

第一步:修改firebase.js,导出需要复用的实例

// FIREBASE INITIALIZATION
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-app.js";
import { getAuth, GoogleAuthProvider } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js";
var firebaseConfig = {
  apiKey: "XXXXXXXXXXXXXXXX",
  authDomain: "XXXXXXXXXXXXXXXX",
  databaseURL: "https://XXXXXXXXXXXXXXXX.firebaseio.com",
  projectId: "XXXXXXXXXXXXXXXX",
  storageBucket: "XXXXXXXXXXXXXXXX.appspot.com",
  messagingSenderId: "XXXXXXXXXXXXXXXX",
  appId: "XXXXXXXXXXXXXXXX"
}
const app = initializeApp(firebaseConfig);
// 初始化Auth实例并导出需要的对象
const auth = getAuth(app);
export { app, auth, GoogleAuthProvider };

第二步:修改custom.js,导入依赖并挂载全局方法

// 从firebase.js导入依赖
import { auth, GoogleAuthProvider } from "./firebase.js";
import { signInWithPopup } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js";

async function signIn(){
  // Sign in using a popup.
  const provider = new GoogleAuthProvider();
  provider.addScope('profile');
  provider.addScope('email');
  const result = await signInWithPopup(auth, provider);

  // The signed-in user info.
  const user = result.user;
  // 修正credential获取方式
  const credential = GoogleAuthProvider.credentialFromResult(result);
  const token = credential.accessToken;
}
// 将函数挂载到window,供内联onclick调用
window.signIn = signIn;

第三步:修改HTML的script标签,给custom.js加上模块属性

<button type="button" name="button" class="btn btn-danger" onclick="signIn()">Login With Google</button>
<script src="js/firebase.js" type="module"></script>
<!-- 新增type="module"属性 -->
<script src="js/custom.js" type="module"></script>

内容的提问来源于stack exchange,提问作者Relaxing Music

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 15:54:00