簡體   English   中英

在 javascript 中登錄 Firebase Auth 時如何將用戶重定向到另一個頁面?

[英]How to redirect user to another page when logged into Firebase Auth in javascript?

我有一個 web 頁面,其中包含 javascript (web) 的 Firebase Auth 服務。 在我的index.html是登錄名:

索引.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Index Page</title>
    <!-- The Firebase JS SDK and SDKs for Firebase products are here -->
    <link rel="stylesheet" href="styles.css">
 </head>
 <body>
    <div id="loginContainer">
        <div id="titleContainer">
            <h1>Login</h1>
        </div>
        <div id="elementsContent">
            <input class="txtBox" id="txtPassword" type="password" placeholder="Password">
            <button class="btn btn-action" id="btnLogin">Submit</button>
        </div>
    </div>
    <script src="app.js"></script>
</body>
</html>

main.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Main Page</title>
    <!-- The Firebase JS SDK and SDKs for Firebase products are here -->
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="formContainer">
        <h1>Welcome!</h1>
        <button id="btnLogout" class="btn hide">Logout</button>
    </div>
    <script src="app.js"></script>
</body>
</html>

應用程序.js

(function() {

// My web app's Firebase configuration are here -------------------

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// References
var database = firebase.database();
var auth = firebase.auth();

// Get elements
const txtPassword = document.getElementById('txtPassword');
const btnLogin = document.getElementById('btnLogin');
const btnLogout = document.getElementById('btnLogout');

// Add login event
btnLogin.addEventListener('click', e => {
    // Get email and pass
    database.ref('emailChild').on('value', function(snapshot) {
        var email = snapshot.val();
        console.log(email);
        const pass = txtPassword.value;
        // Sign in
        const promise = auth.signInWithEmailAndPassword(email, pass);
        promise.catch(e => console.log(e.message));
    });
});

btnLogout.addEventListener('click', e => {
    auth.signOut();
});

// Add event listener
auth.onAuthStateChanged(user => {
    if(user) {
        console.log(user);
    } else {
        console.log('not logged in');
    }
});

}());

我想做但我不知道該怎么做如下:

  1. 登錄時,重定向到main.html頁面。
  2. main.html我有一個注銷按鈕。 我希望按鈕重定向到index.html

在我的登錄中,只有密碼文本框,即我從數據庫中檢索到的 email 並且沒有注冊選項。 我是唯一的用戶(只是將代碼放在上下文中)。

您可以使用 location.href = 'url' 進行重定向

注冊成功后使用重定向到索引頁面

location.href = 'main.html'

你應該在 promise 像這樣解決之后這樣做。 promise.then(() => { location.href = 'main.html' }

同樣點擊注銷按鈕后

location.href = 'index.html'

!!! 照顧相對和絕對網址

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM