javascript - 我正在为我的应用程序使用 Firebase 身份验证。似乎存在无限循环,页面不断被重定向

标签 javascript html firebase firebase-authentication

下面的函数是在用户登录时将用户重定向到“Select Stream.html”。它不断地一遍又一遍地替换位置。

firebase.auth().onAuthStateChanged(function(user) {
    if (user) {
        window.location.replace("Select Stream.html");
      // User is signed in.
    } else {
      // No user is signed in.
      window.location.replace("index.html");
    }
  });

我是编码新手。

Here is the Log in Function

function login()
{
    var userEmail=document.getElementById("email-field").value;
    var userPassword=document.getElementById("password-field").value;

    firebase.auth().signInWithEmailAndPassword(userEmail, userPassword).catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        
      /*  window.location='Select Stream.html'; */
        window.alert("Error : " + errorMessage);
        // ...
      });
}


The Login function will be triggered when the signin-button is clicked.
<input onclick="login()" type="submit" name="signin-button" value="Sign In"/>

最佳答案

首先,将 Select Stream.html 的名称更改为不含空格或大写字母。这是常见的做法,我建议将文件名更改为 select_stream.html

在打开select_stream.htmlindex.html之前,检查用户是否已经在该页面上以防止页面刷新,如下所示:

if (user) {
  // User is signed in.
  if(window.location.href.indexOf("select_stream.html") == -1){
    window.location.replace("select_stream.html");
  }
} else {
  // No user is signed in.
  if(window.location.href.indexOf("index.html") == -1){
    window.location.replace("index.html");
  }
}

window.location.href 变量引用当前页面的 URL,.indexOf 函数允许您检查 URL 中是否包含某个值。如果在字符串中找不到指定的值,.indexOf 函数将返回 -1,因此此代码仅在用户尚未位于重定向页面时进行重定向。

关于javascript - 我正在为我的应用程序使用 Firebase 身份验证。似乎存在无限循环,页面不断被重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55255934/

相关文章:

android - Firebase OnSuccessListener 在应该失败时被调用

php - 如何从另一个 php 页面更改一个页面的标签文本?

javascript - $state.go ("Any url and not just a State ")

javascript - 第一张图片显示弹出窗口,而不是其他图片

javascript - 使用jquery获取相对于图片的点击坐标

java - 如何在单击 Android 中的 Firestore 时删除 ListView 文档?

javascript - 如何使 NVD3 图表具有响应能力?

HTML 文本区域水平滚动

javascript - 从 div 元素中读取一个数字值并四舍五入到小数点后两位

ios - Firebase 消息传递不适用于 iOS 中的 "data"消息