我正在尝试实施Firebase Auth以在Web应用上登录用户,并在单击按钮时将其注销。
我的登录代码是Firebase示例应用中提供的代码,可在此处找到:https://github.com/firebase/quickstart-js/blob/master/auth/email.html
我只添加了一行,以便在登录后重定向到另一个页面:
window.location = 'home.html';
这里:
function initApp() {
// Listening for auth state changes.
// [START authstatelistener]
firebase.auth().onAuthStateChanged(function(user) {
// [START_EXCLUDE silent]
document.getElementById('quickstart-verify-email').disabled = true;
// [END_EXCLUDE]
if (user) {
window.location = 'home.html';
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
这部分有效。问题是在登录后,当它将我重定向到home.html时,它会自动将我带回index.html并将我注销。
我的home.html代码如下所示:
Javascript:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var providerData = user.providerData;
// ...
} else {
// User is signed out.
// ...
window.location = 'index.html';
}
});
document.getElementById("sign-out").onclick = function toggleSignOut() {
firebase.auth().signOut().then(function() {
console.log('Signed Out');
window.location = 'index.html';
}, function(error) {
console.error('Sign Out Error', error);
});
}
带有注销按钮的HTML代码:
<div id="menu">
<button id="sign-out" name="signout">Sign out</button>
</div>
答案 0 :(得分:1)
尝试以下来自 here
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
.then(() => {
// Existing and future Auth states are now persisted in the current
// session only. Closing the window would clear any existing state even
// if a user forgets to sign out.
// ...
// New sign-in will be persisted with session persistence.
return firebase.auth().signInWithEmailAndPassword(email, password);
})
.catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
});
答案 1 :(得分:0)
我相信您的问题是未正确初始化“ home.html”上的“ firebase.auth”对象。我了解您正在使用“观察者”方法确定已登录/已退出,但是据我所知,您在初始化“ home.html”中的“ firebase.auth”对象时无处可去。这可能导致它注销,因为firebase.auth没有上下文可以在该页面上查找用户,因此假定没有用户并注销您,并按预期将您带回到index.html。
您的解决方案是在观察者附件之前添加它:
dirtokeep