Javascript 用户成功登录后,如何将登录页面重定向到主页?

Javascript 用户成功登录后,如何将登录页面重定向到主页?,javascript,html,css,firebase,authentication,Javascript,Html,Css,Firebase,Authentication,我有很多麻烦重定向用户从登录页面到主页后,他们成功登录(使用他们创建的正确电子邮件和密码。我的网站是用HTML、CSS和Javascript编写的,我正在使用firebase进行身份验证。我到处检查,但似乎找不到有效的解决方案。我尝试了以下方法(最后一个功能是尝试重定向)它看起来很有效,但是,它会导致页面无限刷新/重新加载。有人能帮我吗 function signUp() { var email = document.getElementById("email&qu

我有很多麻烦重定向用户从登录页面到主页后,他们成功登录(使用他们创建的正确电子邮件和密码。我的网站是用HTML、CSS和Javascript编写的,我正在使用firebase进行身份验证。我到处检查,但似乎找不到有效的解决方案。我尝试了以下方法(最后一个功能是尝试重定向)它看起来很有效,但是,它会导致页面无限刷新/重新加载。有人能帮我吗

function signUp() {
      
   var email = document.getElementById("email");
   var password = document.getElementById("password");

   const promise = auth.createUserWithEmailAndPassword(email.value, password.value);
   promise.catch(e => alert(e.message));

   alert("Registered");

}

function signIn() {
      
   var email = document.getElementById("email");
   var password = document.getElementById("password");

   const promise = auth.signInWithEmailAndPassword(email.value, password.value);
   promise.catch(e => alert(e.message));

   alert("Logged in " + email.value);

}

function signOut() {
   auth.signOut();
   alert("Logged out");
}

firebase.auth().onAuthStateChanged(function (user) {
   if (user) {
      var email = user.email;
      alert("Active user: " + email);
      window.location.href = "/Users/Me/Desktop/Website HTML/home.html";
   }
   else {
     alert("No active user");
     window.location.href = "/Users/Me/Desktop/Website HTML/login.html";

   }
})

我认为您的代码导致无限重定向循环的原因是因为它没有指定何时不应该发生重定向

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        var email = user.email;
        alert("Active user: " + email);
        if (window.location.href.indexOf("home.html") == -1) {
            window.location.href = "/Users/Me/Desktop/Website HTML/home.html";
        }
    } else {
        alert("No active user");
        if (window.location.href.indexOf("login.html") == -1) {
            window.location.href = "/Users/Me/Desktop/Website HTML/login.html";
        }
    }
})

您应该在signIn方法上执行重定向

const promise = auth.signInWithEmailAndPassword(email.value, password.value);

promise
  .then(() => {
    //handle your redirection here

    //add any alerts or console logs here
  })
  .catch(e => alert(e.message));

//on another note.. the alert you have here will always trigger before
//the promise resolves, so you should have it inside the 'then' method
alert("Logged in " + email.value);
然后仅使用“onAuthStateChanged”方法检查身份验证

firebase.auth().onAuthStateChanged(function (user) {
 if(!user) 
 {
   alert("No active user");
   window.location.href = "/Users/Me/Desktop/Website HTML/login.html";
 }
})

这回答了你的问题吗?哦,我无法告诉你我有多感激!非常感谢!非常感谢!我使用Martin的解决方案进行注册和登录,效果非常好,但是,我的注销位继续循环,所以我使用了你的解决方案进行注销功能,一切都很好!我非常感谢你们两位,因为我一直在努力在这个问题上领导的时间太长了