对接HTML联系表单与Firebase时报错firebase is not defined如何解决
问题原因
- 你当前引入的是Firebase 9+ 模块化版本SDK,该版本废弃了v8及更早版本的全局
firebase命名空间写法,你main.js中使用的firebase.database().ref()是旧版本API,和当前SDK版本不兼容。 <script type="module">标签内的所有变量都是模块私有作用域,不会挂载到window全局对象,外部普通脚本引入的main.js无法访问模块内初始化的Firebase实例。
解决方案
按以下步骤修改即可解决报错:
1. 修改index.html中的Firebase配置和脚本引入
首先在Firebase的模块脚本中导入Realtime Database相关依赖,同时将main.js也设置为模块类型引入,修改后的代码如下:
<script type="module"> import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js"; import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-analytics.js"; // 新增导入Realtime Database方法 import { getDatabase } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-database.js"; const firebaseConfig = { apiKey: "xxxxx", authDomain: "xxxxx", projectId: "xxxxx", storageBucket: "xxxxx", messagingSenderId: "xxxxx", appId: "xxxxx", measurementId: "xxxxx" }; // 初始化Firebase和数据库 const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); const db = getDatabase(app); // 将数据库实例挂载到全局,方便main.js调用 window.db = db; </script> <!-- 给main.js加上module类型 --> <script type="module" src="main.js"></script>
2. 修改main.js代码适配Firebase 9模块化API
替换原有main.js的全部内容,使用新版API完成逻辑:
// 导入数据库操作需要的方法 import { ref, push, set } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-database.js"; const emailRef = ref(window.db, 'emails'); // 监听表单提交 document.getElementById('contactForm').addEventListener('submit', submitForm); // 提交表单逻辑 function submitForm(e){ e.preventDefault(); var FullName = getInputval('FullName'); var Email = getInputval('Email'); saveMessage(FullName,Email); document.querySelector('.alert').style.display = 'block'; setTimeout(function(){ document.querySelector('.alert').style.display = 'none'; },3000); document.getElementById('contactForm').reset(); } // 获取表单值工具函数 function getInputval(id){ return document.getElementById(id).value; } // 保存数据到Firebase function saveMessage(Fullname, Email){ const newEmailRef = push(emailRef); set(newEmailRef, { Fullname: Fullname, Email: Email }); }
内容的提问来源于stack exchange,提问作者Gibson Raphael
相关产品推荐
相关产品推荐

