Firebase身份认证报错:Uncaught ReferenceError: firebase is not defined 求解
Firebase身份认证报错:
firebase is not defined 解决方法 报错信息
Uncaught ReferenceError: firebase is not defined at HTMLFormElement.process (eval at safeAsyncFunction (livewire.js?id=e2b302e9:1249:21),
:32:44)
你的代码实现
<script> const phoneInputField = document.querySelector("#phone"); function getIp(callback) { fetch('https://ipinfo.io/json?token=af99e3dad456d9', { headers: { 'Accept': 'application/json' }}) .then((resp) => resp.json()) .catch(() => { return { country: 'us' }; }) .then((resp) => callback(resp.country)); } const phoneInput = window.intlTelInput(phoneInputField, { initialCountry: "auto", geoIpLookup: getIp, utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js", }); document.getElementById("form").addEventListener("submit", process, false); function process(event) { event.preventDefault(); // Extract formatted phone number const phoneNumber = phoneInput.getNumber(); // Log phone number for debugging purposes console.log("Formatted Phone Number:", phoneNumber); window.recaptchaVerifier = new firebase.auth.RecaptchaVerifier('recaptcha-container', { 'size': 'normal', 'callback': (response) => { // reCAPTCHA solved, allow signInWithPhoneNumber. sendOTP(phoneNumber); }, 'expired-callback': () => { // Response expired. Ask user to solve reCAPTCHA again. // ... } }); } function sendOTP(phoneNumber) { var appVerifier = window.recaptchaVerifier; firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier) .then((confirmationResult) => { // SMS sent. Prompt user to type the code from the message, then sign the // user in with confirmationResult.confirm(code). window.confirmationResult = confirmationResult; // ... }).catch((error) => { // Error; SMS not sent // ... }); } </script> <script type="module"> // Import the functions you need from the SDKs you need import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.1/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/10.12.1/firebase-analytics.js"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: "AIzaSyCYcbJ2OeXyp70VvBvK7jiepIah04S4bic", authDomain: "fir-local-cf48d.firebaseapp.com", projectId: "fir-local-cf48d", storageBucket: "fir-local-cf48d.appspot.com", messagingSenderId: "627101199334", appId: "1:627101199334:web:908a6f01f6bef042134427", measurementId: "G-CNLBT10S5Y" }; // Initialize Firebase const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); </script>
解决步骤
1. 导入并初始化Firebase Auth模块
你用的是Firebase模块化SDK,但只导入了基础的App和Analytics模块,缺少Auth相关的核心方法。修改你的module脚本,补充Auth模块的导入和初始化:
<script type="module"> import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.1/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/10.12.1/firebase-analytics.js"; // 新增:导入Auth相关核心方法 import { getAuth, RecaptchaVerifier, signInWithPhoneNumber } from "https://www.gstatic.com/firebasejs/10.12.1/firebase-auth.js"; const firebaseConfig = { // 你的配置信息保持不变 apiKey: "AIzaSyCYcbJ2OeXyp70VvBvK7jiepIah04S4bic", authDomain: "fir-local-cf48d.firebaseapp.com", projectId: "fir-local-cf48d", storageBucket: "fir-local-cf48d.appspot.com", messagingSenderId: "627101199334", appId: "1:627101199334:web:908a6f01f6bef042134427", measurementId: "G-CNLBT10S5Y" }; const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); // 新增:初始化Auth实例 const auth = getAuth(app); // 把Auth实例和方法挂载到window,供非module脚本调用 window.auth = auth; window.RecaptchaVerifier = RecaptchaVerifier; window.signInWithPhoneNumber = signInWithPhoneNumber; </script>
2. 修改主脚本中的Firebase调用逻辑
原来的代码用了旧版命名空间写法(firebase.auth()),但模块化SDK没有全局firebase对象,改成使用挂载到window的实例和方法:
<script> // ... 其他代码保持不变 function process(event) { event.preventDefault(); const phoneNumber = phoneInput.getNumber(); console.log("Formatted Phone Number:", phoneNumber); // 改用window上的RecaptchaVerifier,必须传入auth实例 window.recaptchaVerifier = new window.RecaptchaVerifier('recaptcha-container', { 'size': 'normal', 'callback': (response) => { sendOTP(phoneNumber); }, 'expired-callback': () => { // 处理验证码过期逻辑 } }, window.auth); } function sendOTP(phoneNumber) { var appVerifier = window.recaptchaVerifier; // 改用window上的signInWithPhoneNumber方法 window.signInWithPhoneNumber(window.auth, phoneNumber, appVerifier) .then((confirmationResult) => { window.confirmationResult = confirmationResult; // ... 后续验证逻辑 }).catch((error) => { // 处理发送验证码失败的错误 }); } </script>
3. 推荐:统一使用module脚本(可选)
把主脚本也改成type="module",可以直接导入Firebase方法,不用挂载到window,代码更整洁规范:
<script type="module"> import { getAuth, RecaptchaVerifier, signInWithPhoneNumber } from "https://www.gstatic.com/firebasejs/10.12.1/firebase-auth.js"; import { initializeApp } from "https://www.gstatic.com/firebasejs/10.12.1/firebase-app.js"; // 初始化Firebase App const firebaseConfig = { // 你的配置信息 apiKey: "AIzaSyCYcbJ2OeXyp70VvBvK7jiepIah04S4bic", authDomain: "fir-local-cf48d.firebaseapp.com", projectId: "fir-local-cf48d", storageBucket: "fir-local-cf48d.appspot.com", messagingSenderId: "627101199334", appId: "1:627101199334:web:908a6f01f6bef042134427", measurementId: "G-CNLBT10S5Y" }; const app = initializeApp(firebaseConfig); const auth = getAuth(app); const phoneInputField = document.querySelector("#phone"); // ... 其他getIp、phoneInput初始化代码不变 document.getElementById("form").addEventListener("submit", process, false); function process(event) { event.preventDefault(); const phoneNumber = phoneInput.getNumber(); const recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', { 'size': 'normal', 'callback': (response) => { sendOTP(phoneNumber, auth, recaptchaVerifier); } }, auth); } function sendOTP(phoneNumber, auth, appVerifier) { signInWithPhoneNumber(auth, phoneNumber, appVerifier) .then((confirmationResult) => { window.confirmationResult = confirmationResult; }).catch((error) => { // 错误处理逻辑 }); } </script>
内容的提问来源于stack exchange,提问作者Srisailam kongalla
相关产品推荐
相关产品推荐

