Uncaught ReferenceError: firebase is not defined

坚强是说给别人听的谎言 提交于 2020-04-16 02:46:13

问题


I am trying to create Google authentication but I copy var provider = new firebase.auth.GoogleAuthProvider(); to my JavaScript and it keeps telling me that Uncaught ReferenceError: firebase is not defined.

Here is my code:

var provider = new firebase.auth.GoogleAuthProvider();

function signin(){

  firebase.auth().signInWithPopup(provider).then(function(result) {

  var token = result.credential.accessToken;
  var user = result.user;

}).catch(function(error) {

  var errorCode = error.code;
  var errorMessage = error.message;
  var email = error.email;
  var credential = error.credential;

}); 
}

回答1:


You are getting this error because firebase variable has not been instantiated and initialized on the page on which you are running the code. To do so you need to -

  1. Include the relevant scripts-

    <script src="https://www.gstatic.com/firebasejs/4.1.3/firebase.js"></script> <script src="https://www.gstatic.com/firebasejs/4.1.3/firebase-auth.js"></script>

firebase.js contains the variable firebase representing your firebase app. firebase-auth.js contains the firebase.auth library which your code is using.

  1. Initialize your app using -

    var config = {
        apiKey: "<API_KEY>",
        authDomain: "<PROJECT_ID>.firebaseapp.com",
        databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
        storageBucket: "<BUCKET>.appspot.com",
        messagingSenderId: "<SENDER_ID>",
    };
    
    firebase.initializeApp(config);
    

To learn more refer - https://firebase.google.com/docs/web/setup




回答2:


One common gotcha with Firebase that would cause this error is if your script loads before Firebase. When using Firebase Hosting for example they create these tags:

  <script defer src="/__/firebase/6.0.2/firebase-app.js"></script>
  ...
  <script defer src="/__/firebase/init.js"></script>

You need to then also load your script using defer

  <script defer src="js/app.js"></script>


来源:https://stackoverflow.com/questions/45656171/uncaught-referenceerror-firebase-is-not-defined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!