I'm making login Authentication with Firebase and I'm testing it with creating a user ID and password on authentication Firebase and test login with that email and password. But I got no response both correct password and wrong password. Please help!
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.5.2/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.5.2/firebase-analytics.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.5.2/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.5.2/firebase-firestore.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "....",
authDomain: "....",
databaseURL: "....",
projectId: "....",
storageBucket: "....",
messagingSenderId: "....",
appId: "....",
measurementId: "...."
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script>
document.getElementById("idLogin").onclick = function() {
var email = document.getElementById('idUser').value;
var password = document.getElementById('idPassword').value;
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function(){
alert('login success');
console.log('success');
}).catch(function(error) {
alert('login fail');
console.log('error');
})
}
</script>
What is most probably happening is that since the element with id="idLogin" is of type submit your form is submitted before the Firebase signInWithEmailAndPassword() method is triggered.
You need to explicitly specify the button type as button, (and not submit) as follows:
<button type="button" id="idLogin">Login</button>
See the W3 specification for more detail.
Related
Am trying to Connect Firebase to a Contact Form,
where requires the user to type and submit Fullname , Email and also Message.
But I face Uncaught ReferenceError: firebase is not defined at my main.js file
form my console.
I tried different solution but I couldn't be able to solve it.
Here is my script tag in my index.html
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.3/firebase-app.js";
</script>
<script src="main.js"></script>
here is my Main.js code
var config = {
apiKey: "xxxxx",
authDomain: "xxxxx",
databaseURL: "xxxxx",
projectId: "xxxxx",
storageBucket: "xxxxx",
messagingSenderId: "xxxxx"
};
firebase.initializeApp(config);
var emailRef = firebase.database().ref('emails');
// Listen for form submit
document.getElementById('contactForm').addEventListener('submit', submitForm);
// Submit form
function submitForm(e){
e.preventDefault();
//Get values
var FullName = getInputval('FullName');
var Email =getInputval('Email');
// save message
saveMessage(FullName,Email);
// Show alert
document.querySelector('.alert').style.display = 'block';
// Hide alert after 3 seconds
setTimeout(function(){
document.querySelector('.alert').style.display = 'none';
},3000);
// Clear form
document.getElementById('contactForm').reset();
}
// Function to get form values
function getInputval(id){
return document.getElementById(id).value;
}
// Save message to firebase
function saveMessage(Fullname, Email,){
var newEmailRef = emailRef.push();
newEmailRef.set({
Fullname: Fullname,
Email:Email
});
}
Since you're initializing firebase here, it should be something like this:
const firebase = initializeApp(config);
For more info you can have a look here.
I am trying to implement FCM notification inside a Flutter Web application but I am getting errors when registering my service worker. I think it might come from the way my files index.html and firebase-messaging-sw.js are made.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>MyApp</title>
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js"></script>
<script>
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
var devConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "DB_URL",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "MESSAGING_SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
// Initialize Firebase
firebase.initializeApp(devConfig);
</script>
<script>
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
navigator.serviceWorker.register("/firebase-messaging-sw.js");
});
}
</script>
<script src="main.dart.js" type="application/javascript"></script>
</body>
</html>
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.5.0/firebase-messaging.js');
var devConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "DB_URL",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "MESSAGING_SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
// Initialize the Firebase app in the service worker by passing in
// your app's Firebase config object.
// https://firebase.google.com/docs/web/setup#config-object
firebase.initializeApp(devConfig);
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function (payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
Errors
Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
at p (https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js:1:10100)
at Object.o [as messaging] (https://www.gstatic.com/firebasejs/7.5.0/firebase-app.js:1:9710)
at http://localhost:56234/firebase-messaging-sw.js:33:28
Uncaught (in promise) TypeError: Failed to register a ServiceWorker for scope ('http://localhost:56234/') with script ('http://localhost:56234/firebase-messaging-sw.js'): ServiceWorker script evaluation failed
I am testing the application using the command flutter run -d web-server.
I am correctly calling await Firebase.initializeApp() before starting my application in my main.dart.
I am using the package firebase_core: ^0.5.0.
I have tested with firebase scripts in version 7.22.1 and 7.5.0.
add follow ing in your index.html
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-messaging.js"></script>
I was reading through Firebase web documentation on reading and writing data from a database, I want to add dynamic counters on my github website so i figured Firebase would be the way to go, I attempted to use code found on the documentation as an example, but the example simply outputs an error "Uncaught SyntaxError: Illegal return statement", below is my testing code i ran, the error occurred at line 22(the return statement)
<body>
<script src="https://www.gstatic.com/firebasejs/7.15.0/firebase-app.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyDsjjwO1Jj0VKeZECp6l2NRgOKy9Yb0fYc",
authDomain: "site-counter-555dd.firebaseapp.com",
databaseURL: "https://site-counter-555dd.firebaseio.com",
projectId: "site-counter-555dd",
storageBucket: "site-counter-555dd.appspot.com",
messagingSenderId: "796019929207",
appId: "1:796019929207:web:51db340ecf1a53891e1672",
measurementId: "G-33WHDZ8X6K"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
<script>
var userId = firebase.auth().currentUser.uid;
return firebase.database().ref('/Downloads' + userId).once('value').then(function(snapshot) {
var username = (snapshot.val() && snapshot.val().username) || 'Anonymous'
});
</script></body>
You're trying to use a return statement that's not within a function. Start by removing the return - there is nothing to return from.
I can't link the function below to my JavaScript file. I am using Firebase CDN code snippet. What am I doing wrong?
Firebase snippet:
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.0.0/firebase-app.js"></script>
<!-- TODO: Add SDKs for Firebase products that you want to use
https://firebase.google.com/docs/web/setup#available-libraries -->
<script src="https://www.gstatic.com/firebasejs/7.0.0/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyAPeU7jO2Zz5kdrh-4g4ehfcrL8Aufzubs",
authDomain: "udemy-modern-javascript-cee40.firebaseapp.com",
databaseURL: "https://udemy-modern-javascript-cee40.firebaseio.com",
projectId: "udemy-modern-javascript-cee40",
storageBucket: "udemy-modern-javascript-cee40.appspot.com",
messagingSenderId: "941299603483",
appId: "1:941299603483:web:afcd4f1da6878b51ef80be",
measurementId: "G-BRYW3TQNLL"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.analytics();
js file:
db.collection('recipes').get().then((snapshot)=>{
console.log(snapshot);
}).catch(err =>{
console.log(err)
});
The error msg is:
sandbox.js:1 Uncaught TypeError: db.collection is not a function at sandbox.js:1 (anonymous) # sandbox.js:1
The db variable from the script tag in your HTML file is not automatically available in the .js file.
You'll typically want to put all JavaScript (including what you now have in the script tag into the .js file or have all of it in the script tag in the HTML file.
Putting all code in the .js file is more common, so that'd become:
var firebaseConfig = {
apiKey: "AIzaSyAPeU7jO2Zz5kdrh-4g4ehfcrL8Aufzubs",
authDomain: "udemy-modern-javascript-cee40.firebaseapp.com",
databaseURL: "https://udemy-modern-javascript-cee40.firebaseio.com",
projectId: "udemy-modern-javascript-cee40",
storageBucket: "udemy-modern-javascript-cee40.appspot.com",
messagingSenderId: "941299603483",
appId: "1:941299603483:web:afcd4f1da6878b51ef80be",
measurementId: "G-BRYW3TQNLL"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
const db = firebase.analytics();
db.collection('recipes').get().then((snapshot)=>{
console.log(snapshot);
}).catch(err =>{
console.log(err)
});
const db = firebase.analytics();
I'm trying to link my contact form in a portfolio website to firebase and keep getting (firebase.database is not a function) in my console
This is for the web, using pure javascript
var firebaseConfig = {
apiKey: "AIzaSyCzX3r8CFw84WSBuCSXR1fWM_hDrwtGMSs",
authDomain: "portfolio-4c243.firebaseapp.com",
databaseURL: "https://portfolio-4c243.firebaseio.com",
projectId: "portfolio-4c243",
storageBucket: "",
messagingSenderId: "745737502175",
appId: "1:745737502175:web:a26e5b0baa3769c9"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
var messagesRef = firebase.database().ref('messages');
document.getElementById('contactForm').addEventListener('submit', submitForm);
function submitForm(e) {
e.preventDefault();
var name = getInputVal('name');
var email = getInputVal('email');
var message = getInputVal('message');
saveMessage(name, email, message);
}
// Function get value
function getInputVal(id) {
return document.getElementById(id).value;
}
//Save
function saveMessage(name, email, message) {
var newMessageRef = messagesRef.push();
newMessageRef.set({
name: name,
email: email,
message: message
})
}
This error is very common and arises because either you have not configured your config object correctly or the script tag required for using that particular functionality is missing.
In your case the config object looks fine so you have to add this script in your page
<script src="https://www.gstatic.com/firebasejs/6.2.4/firebase-database.js"></script>
But please note that this script is to be added only after the core script for firebase app
<script src="https://www.gstatic.com/firebasejs/6.2.4/firebase-app.js"></script>
and for future if you want to use any other service from Firebase like Firestore or so, just make sure you have that particular script tag in there (with the config object correctly setted up).