Javascript 登录到主页的登录页后未获取firebase用户凭据
我正在尝试使用firebase auth和纯Javascript进行简单的登录和注销,我不确定这是否正确。但我到目前为止所做的是:Javascript 登录到主页的登录页后未获取firebase用户凭据,javascript,firebase,firebase-authentication,Javascript,Firebase,Firebase Authentication,我正在尝试使用firebase auth和纯Javascript进行简单的登录和注销,我不确定这是否正确。但我到目前为止所做的是: index.html在我的头元素中已经有了所有必要的导入链接(firebase应用程序、firebase auth) app.js const db = firebase.firestore(); const auth = firebase.auth(); var user = firebase.auth().currentUser; function signI
index.html
在我的头元素中已经有了所有必要的导入链接(firebase应用程序、firebase auth)
app.js
const db = firebase.firestore();
const auth = firebase.auth();
var user = firebase.auth().currentUser;
function signIn(){
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
firebase.auth().signInWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
alert("Sign In");
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
alert(errorMessage);
});
}
function logOut() {
// [START auth_sign_out]
firebase.auth().signOut().then(() => {
alert("Log out");
}).catch((error) => {
// An error happened.
alert(error);
});
// [END auth_sign_out]
}
//[START auth_state_listener]
firebase.auth().onAuthStateChanged((user) => {
if (user) {
location.replace("home.html");
document.getElementById("email").innerHTML = user.email
} else {
// User is signed out
// ...
location.replace("index.html");
}
});
我试图实现的是,当我使用firebase身份验证中已有的电子邮件和密码登录时,我将被重定向到我的
home.html
,它将显示我的电子邮件,如果用户未登录home.html
将无法访问,并且只显示index.html
该代码现在的情况是,在我输入电子邮件和密码后,将出现一个循环,其中页面将不断显示
index.html
和home.html
,并且不会显示电子邮件<h1 id="email"></h1>
<button onclick="logOut()">Logout</button>
<script src="app.js"></script>
const db = firebase.firestore();
const auth = firebase.auth();
var user = firebase.auth().currentUser;
function signIn(){
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
firebase.auth().signInWithEmailAndPassword(email, password)
.then((userCredential) => {
// Signed in
var user = userCredential.user;
alert("Sign In");
})
.catch((error) => {
var errorCode = error.code;
var errorMessage = error.message;
alert(errorMessage);
});
}
function logOut() {
// [START auth_sign_out]
firebase.auth().signOut().then(() => {
alert("Log out");
}).catch((error) => {
// An error happened.
alert(error);
});
// [END auth_sign_out]
}
//[START auth_state_listener]
firebase.auth().onAuthStateChanged((user) => {
if (user) {
location.replace("home.html");
document.getElementById("email").innerHTML = user.email
} else {
// User is signed out
// ...
location.replace("index.html");
}
});