My aim is to be able to retrieve certain values from a realtime database on firebase via javascript. I have everything configured and it works perfectly,but I don't know how to retrieve the individual fields when I click a simple button.
This is an example of the values I would like to be able to take
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button type="submit" id="searchData" class="btn btn-primary">Search data</button>
</body>
</html>
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.8/firebase-app.js";
import { getDatabase, set, ref ,push, child, onValue} from "https://www.gstatic.com/firebasejs/9.6.8/firebase-database.js";
const firebaseConfig = {
apiKey: "********************************",
authDomain: "********************************",
databaseURL: "********************************",
projectId: "********************************",
storageBucket: "****************************",
messagingSenderId: "******************",
appId: "********************************"
};
const app = initializeApp(firebaseConfig);
const db = getDatabase(app);
searchData.addEventListener('click',(e) => {
//
});
</script>
you can try using this example I always implement, note my main file is users, then my key value as id is userId then I have the attributes username and useremail. Try this:
I want to obtain a name:
const dbRef=ref(db, 'users/'+userId);
onValue(dbRef, (snapshot)=>{
const data=snapshot;
for(let i in data){
console.log(snapshot.val().username);
txtCont.innerHTML=`<p>${snapshot.val().username}</p>`;
}
});
Related
I am trying to integrate google auth from Firebase into my web app (on GAS), and i am having a hard time. I am new to it and have few experience in developing so excuse my lack of precision.
I managed to implement several steps but fail to come back to navigate the app normally once the user has logged.
First, here are the steps that are working fine (at least they seem to):
doGet() returns HtmlService.createHtmlOutputFromFile('auth') which contains all the necessary code for the authentication.
'auth.html' calls necessary stuff from firebase via CDN and the behaviour is correct: if i am not logged: UI shows and if i am logged: user details show on screen.
Since i need the userID to go on with the server-side scripts, i pass the userID which for now is just used to check i have the value on server side (is that correct to use userID this way?);
EDITED QUESTION:
Now what i would like to understand is the best practice for the steps
User opens app
doGet() is run and loads 'auth.html'
client-side authentication runs and collects user data
userID is set as a variable to be passed to server
then in order to run the rest of the scripts (the real app content user needs to see) what is the way to go? Should some function be run through google.script.run.someFunction(userID) when user is logged that would run the 'normal' app content (as it was before i integrated any authentication to be clear)?
last question: Does the authentication needs to be run on every page before loading content?
Here is my code:
.gs
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('auth2')
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL)
.setTitle('FirebaseUI | Firebase Authentication');
}
auth.html
<base target="_top">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.14.2/firebase-auth.js"></script>
<script src="https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.css" />
<script>
var firebaseConfig = {
apiKey: "stackoverflow",
authDomain: "stackoverflow.firebaseapp.com",
databaseURL: "https://stackoverflow-default-rtdb.europe-west1.firebasedatabase.app",
projectId: "stackoverflow",
storageBucket: "stackoverflow.appspot.com",
messagingSenderId: "267227785525",
appId: "1:stackoverflow:web:stackoverflow",
measurementId: "G-stackoverflow"
};
firebase.initializeApp(firebaseConfig);
</script>
<script>
google.script.run.withSuccessHandler(function(url) {
var uiConfig = {
signInFlow: 'redirect',
signInSuccessUrl: url,
signInOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID
],
};
var ui = new firebaseui.auth.AuthUI(firebase.auth());
var user = firebase.auth().currentUser;
console.log(user);
if (user) {
document.getElementById("signOut").style.display = "inline-block";
} else {
ui.start('#firebaseui-auth-container', uiConfig);
}
})
.webAppUrl();
</script>
<script>
initApp = function() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
user.getIdToken().then(function(accessToken) {
document.getElementById('account-details').textContent = JSON.stringify({
displayName: user.displayName,
email: user.email,
custom: user.email,
emailVerified: user.emailVerified,
phoneNumber: user.phoneNumber,
photoURL: user.photoURL, // remove quotes to get the photoURL
uid: user.uid,
accessToken: "hidden", // replace "hidden" with accessToken
providerData: user.providerData // remove quotes to get the photoURL
}, null, ' ');
});
const userID = user.email;
google.script.run.someFunction(userID);
} else {
document.getElementById('account-details').textContent = '';
}
});
};
window.addEventListener('load', function() {
initApp();
});
</script>
</head>
Here the documentation i read:
https://developers.google.com/apps-script/guides/html/communication
https://firebase.google.com/docs/auth/web/google-signin
I am trying to post the data from a moisture sensor on a website. I am using Arduino to update and send the data to a Real-Time Firebase database. From there I am using Glitch.com for my website. I am using a moisture sensor, and have the variable 'Moisture' in my database where the values are stored and updated every 0.3 seconds. I currently have the following code:
HTML File
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/styles.css">
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-messaging.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "xx",
authDomain: "xx",
databaseURL: "xx",
projectId: "xx",
storageBucket: "xx",
messagingSenderId: "xx",
appId: "xx"
};
firebase.initializeApp(config);
</script>
<script>
var database = firebase.database();
var ref = firebase.database().ref("plant-patrol/Moisture");
ref.once("value")
.then(function(snapshot) {
var key = snapshot.key; // "plant-patrol"
var childKey = snapshot.child("plant-patrol/Moisture").key; // "Moisture"
});
</script>
<script>
var ref = firebase.database().ref("plant-patrol/Moisture");
ref.on("value", function(snapshot) {
console.log(snapshot.val());
}, function (error) {
console.log("Error: " + error.code);
});
</script>
<script src="/script.js" defer></script>
</head>
</html>
JS File
auth.onAuthStateChanged(currentUser => console.log(currentUser));
auth.signInAnonymously();
I have no idea what this JS code does, but I copied it from another question on Stack Overflow.
Now as stated before, the path in the Realtime Firebase db I want to display is 'Moisture', that is also the only data in the db. I have tried messing around a bit with the childkey and snapshot, and tried reading into what they actually do. Sadly I was not able to display any form of data, not even in the console.
The read & write lines in Firebase have both been set to True as security is not relevant (school project). I was also wondering if it is possible to update the data on the website without having to refresh the page.
Update
Made a bit of progress,read my comments below!
This question already has answers here:
firebase.database is not a function
(9 answers)
Closed 3 years ago.
I am working on an application for android that lets people login and add their data for an amusement park and I also need an app to view the data stored in the database (such as name, birthdate, children etc) on a PC. I have tried to write a web app but I have a problem connecting it to the database. I am new to databases so it might be from my code, can someone help me? The app only needs to show me the database all the time and update when a person registers.
Currently, I am getting this error:
Uncaught TypeError: firebase.database is not a function
at index.html:33
at index.html:66
Here is my index.html file:
<html>
<head>
<meta charset="utf-8"/>
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-analytics.js"></script>
<title>Freaky Firebase Example</title>
</head>
<body>
<h1>Freaky Firebase Realtime Database Example</h1>
<pre id='object'></pre>
<script>
(function(){
// Initialize Firebase
var firebaseConfig = {
apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX.com",
databaseURL: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX.com",
projectId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
storageBucket: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX.com",
messagingSenderId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
appId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
measurementId: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
var userDataRef = firebase.database().ref("UserData").orderByKey();
userDataRef.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var key = childSnapshot.key;
var childData = childSnapshot.val();
var name_val = childSnapshot.val().Name;
var id_val = childSnapshot.val().AssignedID;
$("#name").append(name_val);
$("#id").append(id_val);
});
});
/* Data Event Listeners Start */
const preObject = document.getElementById('object');
const dbRefObject = firebase.database().ref().child('object');
dbRefObject.on('value', snap => {
console.log(snap.val());
preObject.innerText = JSON.stringify(snap.val(), null, 3);
}, function(error) {
// The fetch failed.
console.error(error);
});
/* Stop */
}());
</script>
</body>
</html>
Along with firebase-app and firebase-analytics, you must import the firebase-database service.
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-database.js"></script>
Trying to follow the google Getting Started With Cloud Firestore on the Web - Firecasts
For some reason I'm getting this error:
Uncaught Error: Cannot instantiate firebase-firestore - be sure to load firebase-app.js first.
But I believe I have everything done as it should be. What is wrong with this?
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://www.gstatic.com/firebasejs/5.5.3/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.3/firebase-firestore.js"></script>
</head>
<body>
<h1 id="hotDogOutput">Hot dog status:</h1>
<input type="textfield" id="latestHotDogStatus">
<button id="saveButton">Save</button>
<script src="./app.js"></script>
</body>
</html>
Javascript
// Initialize Firebase
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "..."
};
firebase.initializeApp(config);
const firestore = firebase.firestore();
const settings = {/* your settings... */ timestampsInSnapshots: true};
firestore.settings(settings);
const docRef = firestore.doc("samples/sandwichData");
const outputHeader = document.querySelector("#hotDogOutput");
const inputTextField = document.querySelector("#latestHotDogStatus");
const saveButton = document.querySelector("#saveButton");
saveButton.addEventListener("click", function () {
const textToSave = inputTextField.value;
console.log("I am going to save " + textToSave + " to Firestore");
docRef.set({
hotDogStatus: textToSave
}).then(function() {
console.log("Status Saved!");
}).catch(function(error) {
console.log("Got an error: ", error)
});
})
Either import the entire firebase.js or just firebase-app.js followed by firebase-firestore.js. What's happening here is that the firebase-firestore.js expects firebase-app.js (The core Firebase client) and not the entire library.
<script src="https://www.gstatic.com/firebasejs/5.5.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.5.3/firebase-firestore.js"></script>
Helpful Guide:
https://firebase.google.com/docs/web/setup
If you are using real time database, then add only these two script srcs:
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.9.3/firebase-database.js"></script>
This is my first attempt working with Firebase storage and I'm following this tutorial provided by Firebase:
https://www.youtube.com/watch?v=SpxHVrpfGgU
I've seem to follow the tutorial step-by-step, however, I'm getting the following error and I can't find a solution for it:
firebase-storage.js:3469 Uncaught Error: No Storage Bucket defined in Firebase Options.
at t.ref (firebase-storage.js:3469)
at HTMLInputElement.<anonymous> (myFile.js:18)
When I click on 't.ref' it leads me to the following catch:
catch(error) {
throw new Error(
'Cannot instantiate firebase-storage.js - ' +
'be sure to load firebase-app.js first.'
)
Here's my HTML:
<!doctype html>
<html lang="en">
<head>
<title>...</title>
<link rel="stylesheet" type="text/css" href="stylesheets.css" />
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://www.gstatic.com/firebasejs/4.1.5/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "",
messagingSenderId: "..."
};
firebase.initializeApp(config);
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<nav>...</nav>
<progress value="0" max="100" id="uploader" style="margin-top: 35px;">0%</progress>
<input type="file" value="uploader" id="fileButton" />
<script src="myFile.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</body>
</html>
And my corresponding Javascript:
// Get elements
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
// Listen for file selection
fileButton.addEventListener('change', function(e) {
// Get file
var file = e.target.files[0];
// Create a storage reference
var storageRef = firebase.storage().ref('mover_docs/' + file.name);
// Upload a file
var task = storage.put(file);
// Update progress bar
task.on('state_changed',
function progress(snapshot) {
var percentage = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
uploader.value = percentage;
},
function error(err) {
},
function complete() {
}
);
});
I guess my primary question is, is this error occurring since the storageBucket found within the initialize Firebase area has an empty value or am I missing something else?
What needed to be done is copy the link within the 'storage' tab on your Firebase projected above your empty file. It looks something similar to this:
gs://projectName-ci4w0.appspot.com/
Now, just remove the gs:// and the last forward slash after .com. Place this newly formed link into the rules sections in Firebase for Storage like so:
match /b/projectName-ci4w0.appspot.com/o {
Finally, place the same new link within the initialization section for Firebase in your code like so:
<script>
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "projectName-ci4w0.appspot.com",
messagingSenderId: "..."
};
firebase.initializeApp(config);
</script>
That's it!
In my case, I simply by inattention added white space at the end of bucket URL. Hope somebody will help this because I spent an half of an hour to find this.
storageBucket: "appname.appspot.com "