Firebase退出登录后页面跳转问题:点击按钮无响应求助
Let's break down what's going wrong here and fix it step by step:
First, your current code has two key issues that are causing the button to do nothing on the first click:
Duplicate event binding: You’ve added an
onclickattribute to the button that callssignout(), but inside that function, you’re adding another click event listener to the same button. That means the first click only sets up the listener—no sign-out logic runs. Only the second click would trigger the sign-out, which is obviously not what you want.Ignoring async behavior:
firebase.auth().signOut()is an asynchronous operation (it returns a Promise). Your original code runsalert()andwindow.locationimmediately after calling it, which means the page might redirect before the sign-out is actually completed. Plus, thealertblocks the thread, which can disrupt the async flow.
Here are two clean solutions to fix this:
Solution 1: Use Event Listener (Recommended)
This is the modern, unobtrusive way to handle events—separating your HTML and JavaScript:
HTML:
<input type="button" name="" value="Sign out" id="btn-action">
JavaScript:
// Wait for the page to fully load before binding the event document.addEventListener('DOMContentLoaded', function() { const signOutBtn = document.getElementById('btn-action'); signOutBtn.addEventListener('click', function(event) { // Trigger sign-out and handle the async response firebase.auth().signOut() .then(() => { // Only run this if sign-out succeeds alert('Successfully signed out!'); window.location.href = 'user.html'; // Ensure this path matches your target page }) .catch((error) => { // Handle any errors (e.g., network issues) console.error('Sign-out failed:', error); alert('Oops, something went wrong. Check the console for details.'); }); }); });
Solution 2: Fix the Existing signout() Function
If you prefer keeping the onclick attribute, rewrite the function to remove the duplicate listener and properly handle the async Promise:
HTML:
<input type="button" name="" value="Sign out" id="btn-action" onclick="signout();">
JavaScript:
function signout() { firebase.auth().signOut() .then(() => { alert('You\'ve been signed out!'); window.location.href = 'user.html'; // Correct the target page path here }) .catch((error) => { console.error('Sign-out error:', error); alert('Failed to sign out. Please try again.'); }); }
Quick Checks to Ensure It Works:
- Verify Firebase Auth is properly initialized in your app (no
firebase is not definederrors in the browser console). - Double-check that
user.htmlexists at the correct path relative to your current page. - Open your browser's developer tools (F12) and check the Console tab for any errors—this will help debug if something’s still not working.
That should get your sign-out button working exactly as you want it to!
内容的提问来源于stack exchange,提问作者Abhishek Kumar

