How to redirect after a user signs in with Firebase authentication?

后端 未结 4 1489
孤独总比滥情好
孤独总比滥情好 2020-12-03 06:35

How can I redirect to a different webpage after the user has signed in?

Currently when a user logs in, data gets retrieved however, it doesn\'t redirect the user to

4条回答
  •  臣服心动
    2020-12-03 06:50

    You just need to add two redirects inside initApp() to make this happen. I’m referring to the quickstart git repo https://github.com/firebase/quickstart-js/blob/master/auth/email.html, as I came here via the duplicate question Redirecting to a page after Firebase login - Javascript

    1) on line 163, add the page you want logged-in users to be redirected to:

    162 //User is signed in.
    163 window.location = ‘loggedIn.html’;
    164 var displayName = user.displayName;
    

    2) on line 180 (now 181 because of the add above), add a redirect back to the login page:

    180 // User is signed out.
    181 window.location = ‘index.html’;
    182 // [START_EXLUDE]
    

    You need to add the entire script to both the index and the logged in pages - so everything (including the script tags) between lines 37 and 201 from the original git repo (but with the two redirect additions above).

    Now, if you try to go directly to loggedIn.html without logging in, the initApp function will check if you are logged in, see that you aren’t, and redirect you to the login page.

    The only issue is you get a quick flash of the logged content before the redirect, so to get around this you could set the body of this page to be hidden, and have a script that runs if the user is logged in that removes the hidden class.

    Lastly, you’ll want to add a redirect inside the toggleSignIn function, on line 46 of the original repo:

    45  firebase.auth().signOut();
    46  window.location = ‘index.html’;
    47  // [END signout]
    

提交回复
热议问题