【问题标题】:Why do I get redirected even after I deleted window.location("url")为什么即使在我删除 window.location("url") 后我也会被重定向
【发布时间】:2021-08-17 12:41:44
【问题描述】:

我创建了一个登录表单并将提交按钮设置为使用window.location.replace("home.html") 重定向到 home.html,我还尝试了window.location.href = "home.html"

<button onclick="signIn()">Sign In</button>

functon signIn(){
    //Username input
    var email = document.getElementById("email");
    //Password input
    var password = document.getElementById("password");
    //Firebase function for signing in
    auth.signInWithEmailAndPassword(email.value, password.value);
}

//If user is signed in
auth.onAuthStateChanged(functon(user){
    if(user){
        window.location.href = "home.html"
    }
    else{
        alert("No credentials")
    }
})

但是,我已经删除了重定向命令和home.html。但只要用户登录,它就会重定向到一个不再存在的页面。即使没有window.location.replace()

  <button onclick="signIn()"></button>


function signIn(){
     // The username input
    const userEmail = document.getElementById("email").value;
    //The password input
    const userPass = document.getElementById("password").value;
    
    //Firebase function for signing in
    auth.signInWithEmailAndPassword(userEmail, userPass).catch((error) => {
            var errorCode = error.code;
            var errorMessage = error.message;
            window.alert("Error: " + errorMessage);
        });
}

结果:

【问题讨论】:

  • type="button" 添加到您的按钮,这样它就不会提交表单。或者,甚至更好(它允许输入提交),对表单提交做出反应,但使用event.preventDefault()
  • 当用户登录时,onAuthStateChanged 会将用户重定向到 home.html

标签: javascript firebase firebase-authentication window.location


【解决方案1】:
const authObserver = auth.onAuthStateChanged(functon(user){
    if(user){
        window.location.href = "home.html"
    }
    else{
        alert("No credentials")
    }
})

您必须取消订阅 Auth 观察者。你有一个评论 //If user is signed in 但实际上这个观察者每次身份验证状态改变时都会运行,即用户登录或退出。

function signIn(){
     // unsubscribing from Auth observer
     authObserver()
  
     // The username input
    const userEmail = document.getElementById("email").value;
}

当调用signIn 函数时,调用authObserver() 将取消订阅身份验证更改,即onAuthStateChanged 将不再重定向用户本身。

【讨论】:

    猜你喜欢
    • 2012-05-29
    • 1970-01-01
    • 2013-08-30
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 2023-04-06
    相关资源
    最近更新 更多