简体   繁体   中英

How to redirect to another page after firebase login using javascript?

I am making a web app using firebase. Till now i have been able to create users and enter their details in firebase database. Now, the problem i am facing is, after logging in, i want the user to be redirected to another page, as shown below. I checked for a similar issue here on stackoverflow and tried to implement it but it is not working. How to do it?

Below is the code:

   var msgRef = firebase.database().ref().child('messages');

   document.getElementById('contactform').addEventListener('submit', 
   submitLogin);

   firebase.auth().onAuthStateChanged(function(user) {
   if (user) {
     window.location = "after-login.html";
   } else {
      document.getElementById("contact").style.display = "block";
   }
  })

  function submitLogin() {
  var userEmail = document.getElementById("email").value;

  var userPass = document.getElementById("password").value;



  firebase.auth().createUserWithEmailAndPassword(userEmail, 
   userPass).catch(function(error) {
     // Handle Errors here.
     var errorCode = error.code;
     var errorMessage = error.message;
     // ...
   });
  }

The stuff i am trying to do is redirect my page after login to "after-login.html". For need of any more references, please do ask.

Redirecting to a page in Javascript can be achieved via

window.location.href = yoururl;

In your case you have a catch , but the catch is that you do not have a then , which will be the callback of your promise. So, call a then and implement the redirect you need inside its callback. See here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises

An example in the source shown above:

doSomething().then(function(result) {
  return doSomethingElse(result);
})
.then(function(newResult) {
  return doThirdThing(newResult);
})
.then(function(finalResult) {
  console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM