I am very confused on how to include Firebase into html - javascript

I recently started integrating firebase into my html project, i installed firebase-tools using npm and initialized the project, but then after I included all the scripts mentioned on the firebase website, I used firebase.auth() to sign in the user, then I got an error that firebase is undefined, so I inserted these script tags into my code:
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/firebase/init.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-app.js"></script>
<!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-analytics.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-firestore.js"></script>
and below these I had my firebase config:
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "MY_API_KEY",
authDomain: "MY_PROJECT.firebaseapp.com",
databaseURL: "https://MY_PROJECT.firebaseio.com",
projectId: "MY_PROJECT",
storageBucket: "MY_PROJECT.appspot.com",
messagingSenderId: "MESSAGER_ID",
appId: "MY_APP_ID",
measurementId: "MEASUREMENT_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script>
async function signIn(email, password){
await firebase.auth().signInWithEmailAndPassword({
email,
password
}).then(() => {window.location.href = "HomeScreen.html"}).catch((err) => {
document.getElementById('FailedSignIn').style.display = "flex";
})
}
</script>
And then I got these errors:
[2020-03-30T17:24:20.332Z] #firebase/app: Warning: Firebase is already defined in the global scope. Please make sure Firebase library is only loaded once.
Website.htmlAccess to fetch at 'https://firebaseinstallations.googleapis.com/v1/projects/MY_PROJECT/installations' from origin 'http://localhost:63342' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
https:/…base-analytics.js:1POST https://firebaseinstallations.googleapis.com/v1/projects/MY_PROJECT/installations net::ERR_FAILED
TypeError: Failed to fetch
So I would really appreciate some clarification of the ordering of these script tags, as well as how to properly initialize firebase and use it in my file without any errors.

After you’ve created your account and the Firebase project, all you need to do is add the JavaScript code to your HTML, as described in the Setup Docs
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script>
// Initialize Firebase
// TODO: Replace with your project's customized code snippet
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);
// Get a reference to the database service
var database = firebase.database();
// update the variable when the starCount is changed in the database
var starCountRef = database.ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
updateStarCount(postElement, snapshot.val());
});
// update the UI
function updateStarCount(el, val) {
el.innerHtml(`${val} Stars!`);
}
</script>
Then you can continue to learn about Realtime Database here
The Javascript/Node.JS SDK is introduced here.

How do you start your local web-server at http://localhost:63342?
Maybe you just have to start your web-server with using CORS request headers for external requests.
Example:
yarn serve --cors

Related

I am seeing following error while trying to add firebase analytics

I have linked firebase analytics to the firebase project recently but I am getting the following error in my console and nothing is visible in the firebase analytics Dashboard even.
[2022-04-11T06:07:13.736Z] #firebase/analytics: The measurement ID in the local
Firebase config (G-XXXXXXXXX) does not match the measurement ID fetched from the
server (undefined). To ensure analytics events are always sent to the correct Analytics
property, update the measurement ID field in the local config or remove it from the
local config.
This is how I am adding analytics
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "*****************",
projectId: "********",
storageBucket: "*********",
messagingSenderId: "********",
appId: "*******************************",
measurementId: "G-XXXXXXXXX"
};
const app = firebase.initializeApp(firebaseConfig)
const auth = getAuth(app)
const db = getFirestore(app)
firebase.analytics()
const analytics = getAnalytics(app);
console.log(analytics)
Can anyone help what exactly I am missing? Any help is appreciated.
If anyone sees this error, then in my case issue was I have implemented firebase analytics after creating the project not while creating. SO it took 24 hours to reflect. And after 24 hours everything was working.

Why my data is not store in firebase database

Here is the whole html and javascript code.
After submiting also my firebase is not showing anydata plzz help....
Enter any number
enter e-mail
enter nick-name
Submit
<!-- The core Firebase JS SDK is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/7.17.1/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.17.1/firebase-analytics.js"></script>
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyALexu52pRX3m0nL92qSNcl9t2ohhIzAS4",
authDomain: "just-demo-373a2.firebaseapp.com",
databaseURL: "https://just-demo-373a2.firebaseio.com",
projectId: "just-demo-373a2",
storageBucket: "just-demo-373a2.appspot.com",
messagingSenderId: "834837235468",
appId: "1:834837235468:web:f3dbef999d51d15612ab29",
measurementId: "G-FEJBSGENTD"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
Here is the javascript.
function button(){
firebase.database().ref("user").set({
userid:document.getElementById("userID").value,
useremail:document.getElementById("email").value,
username:document.getElementById("name").value
});
}
what should I do?
I created a fiddle for this at: https://jsfiddle.net/raddevus/sqm3og1r/5/
When I click the Test button (I added) I see an error in the console that states:
firebase.database is not a function
Is that a valid call. The initialize seems to be running, but not that database call.

Firebase Cloud Firestore Admin SDK issue

I am trying to update a Firebase document by first logging in with the admin account using Firebase Auth SDK.
Next I use the Firestore SDK to pull down the different parts of data needed from that plan.
Then push them back up to the new plan. So it’s essentially duplicating the plan.
The way I used to do it was in a self invoking function at the bottom of a HTML and just load the SDKs from their CDN.
Instructions to setup and links to CDN: https://firebase.google.com/docs/web/setup
If you try doing the
const firebaseConfig = {
apiKey: 'api-key',
authDomain: 'project-id.firebaseapp.com',
projectId: 'project-id',
}
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
db.collection("users").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// console.log(`${doc.othre} => ${doc.data()}`);
console.log(doc);
});
})
i get the follow error
Uncaught (in promise) FirebaseError: Missing or insufficient permissions.
If you want to use the Admin SDK from a server, please look at the doc for more details, in particular firebase.google.com/docs/admin/setup#prerequisites.

Unable data in firebase - Error: FIREBASE FATAL ERROR: Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com

I am unable to save data to firebase from a news api. I can fetch successfully but when I add my save function it returns this error:
Error: FIREBASE FATAL ERROR: Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com
See below my code:
exports.getArticles = functions.https.onRequest((req, res) => {
return request(newsURL)
.then(data => save(data))
.then(data => response(res, data, 201))
});
function request(url) {
return new Promise(function (fulfill, reject) {
client.get(url, function (data, response) {
fulfill(data)
})
})
}
function response(res, data, code) {
return Promise.resolve(res.status(code)
.type('application/json')
.send(data))
}
function save(data) {
return admin.database().ref('/feed/news')
.set({ data: data })
.then(() => {
return Promise.resolve(data);
})
}
const admin = require('firebase-admin');
var serviceAccount = require('../serviceaccount.json');
admin.initializeApp({ credential: admin.credential.cert(serviceAccount), databaseURL: 'console.firebase.google.com/project/yara-96b67/overview' });
const db = admin.firestore();
module.exports = { admin, db };
Inside the initializeApp, you need to use the following:
// Initialize default app
// Retrieve your own options values by adding a web app on
// https://console.firebase.google.com
firebase.initializeApp({
apiKey: "AIza....", // Auth / General Use
authDomain: "YOUR_APP.firebaseapp.com", // Auth with popup/redirect
databaseURL: "https://YOUR_APP.firebaseio.com", // Realtime Database
storageBucket: "YOUR_APP.appspot.com", // Storage
messagingSenderId: "123456789" // Cloud Messaging
});
The above is a sample from the documentation, but the property databaseUrl, should take the url of the realtime database that contains ..firebaseio.com in the end.
You can find the url by entering the firebase console and going to the database section.
I ran into this error when setting up a project in the EU. In my case it was due to following a tutorial that hadn't been updated in a year or two and was using an older version of the Firebase SDK. The solution was to update my CDN links as listed here:
https://firebase.google.com/docs/web/setup?hl=en#add-sdks-initialize
Contents as of this writing:
<body>
<!-- Insert these scripts at the bottom of the HTML, but before you use any Firebase services -->
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-app.js"></script>
<!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-analytics.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.3/firebase-firestore.js"></script>
</body>
For anyone who ran into this error while using Firebase with Flutter project:
If you have used $ flutterfire configure to configure firebase to your flutter project as shown in here before adding Realtime Database, you will have to run the command again to reconfigure your project or add "databaseURL" to the FirebaseOptions in your lib/firebase_options.dart.
Your lib/firebase_options.dart should look something like this:
// inside lib/firebase_options.dart
// ...
static const FirebaseOptions web = FirebaseOptions(
apiKey: '...',
appId: '...',
messagingSenderId: '...',
projectId: 'project-id',
authDomain: 'project-id.firebaseapp.com',
databaseURL: 'https://your-database-id.firebasedatabase.app', // IMPORTANT!
storageBucket: 'project-id.appspot.com',
measurementId: '...',
);
// ...
For any new folks reading this question.
Google creates databaseURL differently for US and EU datacenters.
for Europe it's ... firebasedatabase.app
for US it's ... firebaseio.com
So, when on database creation step, Google asks you where database should be located? -> don't select EU
At least not until all middleware developers update their code to support different URL pattern in Firebase Config. :)

Sending data to Firebase database from Javascript

I am very new in javascript and Firebase Database, and I cant quite comprehend how to send data to my database from it. I am sending data from an html document and I know how to record the information in to a variable, but now I want to send it to firebase and I dont know how to initialize the Firebase Database from Javascript. Thank you.
You need to use JavaScript SDK of Firebase.
Configure you app first.
<script src="https://www.gstatic.com/firebasejs/4.5.0/firebase.js"></script>
<script>
// Initialize Firebase
// TODO: Replace with your project's customized code snippet
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);
</script>
To read data:
firebase.database().ref('/list').once('value').then(function(data) {
// ...
});
read this documentation for more details:
Add Firebase to your JavaScript Project

Categories

Resources