我创建了一个名为index.html的signIn页面。当用户登录时,我希望在名为home.html的新页面中重定向,显示当前用户的电子邮件。
问题是我得到一个null currentUser。
file:index.html
<html>
<head>
<title>Firebase Login</title>
<link href="https://fonts.googleapis.com/css?family=Nunito:400,600,700" rel="stylesheet">
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="login_div" class="main-div">
<h3>Firebase Web login Example</h3>
<input type="email" placeholder="Email..." id="email_field" />
<input type="password" placeholder="Password..." id="password_field" />
<button onclick="login()">Login to Account</button>
</div>
<script src="https://www.gstatic.com/firebasejs/4.8.1/firebase.js">
</script>
<script>
// Initialize Firebase
var config = {
apiKey: "XXXXXX",
authDomain: "XXXX",
databaseURL: "XXXX",
projectId: "XXXXX",
storageBucket: "XXXXX",
messagingSenderId: "XXXX"
};
firebase.initializeApp(config);
</script>
<script src="index.js"></script>
</body>
</html>
file:index.js
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var user = firebase.auth().currentUser;
if(user != null){
var email_id = user.email;
window.location.href = "home.html"; //(!!!!!! REDIRECT)
document.getElementById("userEmail).innerHTML = email_id;
}
} else {
// No user is signed in.
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
function login(){
var userEmail = document.getElementById("email_field").value;
var userPass = document.getElementById("password_field").value;
firebase.auth().signInWithEmailAndPassword(userEmail, userPass).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error : " + errorMessage);
// ...
});
}
file home.html
<!DOCTYPE html>
<html>
<body>
<div id="userEmail"></div>
</body>
在home.html文件中,当前用户具有空值。
如何在#userEmail(home.html)中显示用户登录的电子邮件?
P.S。我已在home.html文件中导入了Firebase脚本。
答案 0 :(得分:0)
以下代码: window.location.href =&#34; home.html&#34 ;; //(!!!!!! REDIRECT) 无法执行。
我希望用这段代码进行无限循环。
尝试在重定向之前检查location.pathname。
if (window.location.pathname !== 'home.html') {
window.location.href = 'home.html'
} else {
// your code here... (insert email into div...)
}
答案 1 :(得分:0)
尝试将用户电子邮件存储在会话中,您可以在任何地方访问它,直到您在注销时将其设为null。
答案 2 :(得分:0)
从你的代码中删除这一行:
var user = firebase.auth().currentUser;
原因是因为此功能应该已经处理当前用户状态:
firebase.auth().onAuthStateChanged