问题
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 -
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.
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