如何在HTML、CSS及JavaScript网站中实现Firebase认证?求推荐最新教程
Hey there! I’ve tackled Firebase Auth in vanilla HTML/CSS/JS projects plenty of times, so let me walk you through this clearly and answer both your questions.
Let’s break this down into actionable, no-fancy-framework steps:
Step 1: Set Up Your Firebase Project
- Head to the Firebase Console, create a new project, and enable the Authentication service.
- Under the "Sign-in method" tab, turn on the auth providers you want (start with Email/Password if you’re new—it’s the simplest to test).
- Grab your Firebase config snippet (found under Project Settings > "Add app" > choose web app, then copy the
firebaseConfigobject).
Step 2: Add Firebase SDKs to Your HTML
Include the necessary Firebase CDN links right before your closing </body> tag (this helps with page load speed):
<!-- Firebase App Core SDK --> <script src="https://www.gstatic.com/firebasejs/9.23.0/firebase-app.js"></script> <!-- Firebase Auth SDK --> <script src="https://www.gstatic.com/firebasejs/9.23.0/firebase-auth.js"></script>
Note: Check Firebase’s official docs for the latest SDK version number to avoid compatibility issues.
Step 3: Initialize Firebase in Your JavaScript
Create a firebase-init.js file (or add this script block directly in your HTML) to connect your site to Firebase:
const firebaseConfig = { apiKey: "YOUR_API_KEY", authDomain: "YOUR_AUTH_DOMAIN", projectId: "YOUR_PROJECT_ID", storageBucket: "YOUR_STORAGE_BUCKET", messagingSenderId: "YOUR_SENDER_ID", appId: "YOUR_APP_ID" }; // Initialize Firebase firebase.initializeApp(firebaseConfig); // Get authentication instance const auth = firebase.auth();
Step 4: Build Auth UI & Add Core Functionality
Create simple HTML forms for registration and login, then hook up the JavaScript logic:
Example Registration Form
<form id="register-form"> <input type="email" id="register-email" placeholder="Your Email" required> <input type="password" id="register-password" placeholder="Your Password" required> <button type="submit">Create Account</button> </form>
Add registration logic to your JS:
document.getElementById('register-form').addEventListener('submit', (e) => { e.preventDefault(); const email = document.getElementById('register-email').value; const password = document.getElementById('register-password').value; auth.createUserWithEmailAndPassword(email, password) .then((userCredential) => { // Registration succeeded: access user data const user = userCredential.user; console.log('New user registered:', user); // Update UI (e.g., redirect to dashboard, show welcome message) }) .catch((error) => { // Handle errors like weak passwords or duplicate emails alert(error.message); }); });
Example Login & Logout
<form id="login-form"> <input type="email" id="login-email" placeholder="Your Email" required> <input type="password" id="login-password" placeholder="Your Password" required> <button type="submit">Login</button> </form> <button id="logout-btn" style="display: none;">Logout</button>
Add login/logout logic:
// Login handler document.getElementById('login-form').addEventListener('submit', (e) => { e.preventDefault(); const email = document.getElementById('login-email').value; const password = document.getElementById('login-password').value; auth.signInWithEmailAndPassword(email, password) .then((userCredential) => { const user = userCredential.user; console.log('User logged in:', user); // Update UI: hide login/register forms, show logout button document.getElementById('login-form').style.display = 'none'; document.getElementById('register-form').style.display = 'none'; document.getElementById('logout-btn').style.display = 'block'; }) .catch((error) => { alert(error.message); }); }); // Logout handler document.getElementById('logout-btn').addEventListener('click', () => { auth.signOut() .then(() => { console.log('User logged out'); // Reset UI: show login/register forms, hide logout button document.getElementById('login-form').style.display = 'block'; document.getElementById('register-form').style.display = 'block'; document.getElementById('logout-btn').style.display = 'none'; }) .catch((error) => { alert(error.message); }); });
Track Auth State Automatically
Add this to your JS to keep your UI in sync with user login status (even after page reloads):
auth.onAuthStateChanged((user) => { if (user) { // User is signed in console.log('Current active user:', user); document.getElementById('login-form').style.display = 'none'; document.getElementById('register-form').style.display = 'none'; document.getElementById('logout-btn').style.display = 'block'; } else { // No user signed in document.getElementById('login-form').style.display = 'block'; document.getElementById('register-form').style.display = 'block'; document.getElementById('logout-btn').style.display = 'none'; } });
Since Firebase updates its SDK regularly, stick to these trusted, recent resources:
- Firebase Official Documentation: The "Get Started with Firebase Authentication on the Web" guide is always the most up-to-date, maintained directly by the Firebase team. It covers vanilla JS implementation and all major auth providers in detail.
- Traversy Media: Their 2023 "Firebase Authentication Tutorial - Full Course" walks through building a complete auth flow with vanilla JS, including form validation and dynamic UI updates.
- Net Ninja: The "Firebase Auth for Beginners" series focuses on practical, step-by-step implementation for vanilla JS projects, covering email/password, Google auth, and state management.
All these resources avoid overcomplicating things and focus exactly on what you need for a basic HTML/CSS/JS site.
内容的提问来源于stack exchange,提问作者Adewole Olumide




