Adding Firebase to JavaScript Project - javascript

I'm trying to programm a Chat Web-Application with Firebase. I am using HTML as a return method in Javascript. I tried to include my DB Firebase but I'm getting an error, that the DB is not defined. Can someone solve my Problem?
function Chats() {
const username = prompt("What's your name?");
document.getElementById("send-message").addEventListener("submit", postChat);
function postChat(e) {
e.preventDefault();
const timestamp = Date.now();
const chatTxt = document.getElementById("chat-txt");
const message = chatTxt.value;
chatTxt.value = "";
db.ref("messages/" + timestamp).set({
usr: username,
msg: message,
});
}
return (
<div id="chat">
<ul id = "messages"></ul>
<form id="send-messages">
<input id="chat-txt" type= "text"></input>
<button id="chat-btn">Submit</button>
</form>
<script src="https://www.gstatic.com/firebasejs/9.8.1/firebase-app.js"></script>
<script src="https://united-parents-default-rtdb.europe-west1.firebasedatabase.app"></script>
</div>
);
}

declare DB variable at start of your script
var db = firebase.database();
first you have to initialize the firebase
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-storage.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.6.1/firebase-functions.js"></script>
<script>
var firebaseConfig = {
apiKey: "api_key",
authDomain: "authDomain",
databaseURL: "databaseURL",
projectId: "projectId",
storageBucket: "storageBucket",
messagingSenderId: "messagingSenderId",
appId: "appId"
};
firebase.initializeApp(firebaseConfig);
</script>
you can get this from firebase console as well

Related

Unable to request permission to fetch device token in javascript

I am trying to fetch my device token in javascript. I have included these imports in my HTML page:
<script src="https://www.gstatic.com/firebasejs/9.10.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.10.0/firebase-database-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.10.0/firebase-messaging-compat.js"></script>
My javascript:
const firebaseConfig = {
messagingSenderId: "MY SENDER ID FROM CONSOLE",
apiKey: "MY API KEY FROM CONSOLE",
authDomain: "domain_name.firebaseapp.com",
projectId: "domain_name",
storageBucket: "domain_name.appspot.com",
messagingSenderId: "01234643924812",
databaseURL: "https://domain_name-default-rtdb.firebaseio.com",
appId: "1:1230535236326:web:f0fc4f32t23t235122e112c800"
};
const app = firebase.initializeApp(firebaseConfig);
(async()=>{
try {
await firebase.messaging().requestPermission();
const token = await messaging.getToken();
console.log('Your token is:', token);
return token;
} catch (error) {
console.error(error);
}
})();
When I execute the code, I get this error:
TypeError: firebase.messaging(...).requestPermission is not a function
What am I doing wrong?

How can I retrieve data from my firebase database?

I have tried many ways to get data from my firebase database, but they dont work.
Is there any simple way to retrieve data from my firebase database?
my js code:
var firebaseConfig = {
apiKey: "REDACTED",
authDomain: "REDACTED.firebaseapp.com",
projectId: "REDACTED",
storageBucket: "REDACTED.appspot.com",
messagingSenderId: "474155068193",
appId: "REDACTED",
measurementId: "G-715TVNY07N"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
console.log(firebase);
var database = firebase.database();
var ref = database.ref('en');
function lah(){
var data = {
kommentti: document.getElementById("viesti").value
}
ref.push(data);
}
my database:
I would like to know what is inside those kommenttis.
If you want to get the data just once without a listener you can use a function like this one:
const getData = async () => {
return firebase
.database()
.ref("en")
.once("value")
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
const childKey = childSnapshot.key;
const childData = childSnapshot.val();
const kommentti = childData.kommentti;
});
});
};

How to resolve this FB firebase auth credential error

The error I gotten was invalid credentials[ remote site 5XX from facebook.com for USER_INFO ] , do I need to initialize the credential and token.
I an using firebase realtime DB and Facebook auth.
I have ensure that the app id and app secret is correct, the Facebook developer web app is also in live mode.
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.2/firebase-analytics.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-database.js"></script>
<script>
var config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
firebase.initializeApp(config);
firebase.analytics()
var database = firebase.database();
var provider = new firebase.auth.FacebookAuthProvider();
function fblogin() {
firebase
.auth()
.signInWithPopup(provider)
.then((result) => {
var user = result.user;
var credential = result.credential;
var accessToken = credential.accessToken;
})
.catch((error) => {
var errorCode = error.code;
alert(errorCode)
var errorMessage = error.message;
alert(errorMessage)
var email = error.email;
var credential = error.credential;
});
}

Firebase Auth to sign-in google not working in Framework7

I have setup Firebase admin structure and generate all required id, key and token. With Firebase email and password auth it works fine. But when implementing Google signin it fails. Please help.
index.html code
`<i class="icon fab fa-google-plus-g"></i>`
<script src="js/firebase.js"></script>
<script src="js/firebase-auth.js"></script>
<script>
// Initialize Firebase
var configfirebase = {
apiKey: "***********************",
authDomain: "*****************.firebaseapp.com",
databaseURL: "https://f*************.firebaseio.com",
projectId: "************",
storageBucket: "************",
messagingSenderId: "**********",
};
firebase.initializeApp(configfirebase);
</script>
registration.js code
var provider = new firebase.auth.GoogleAuthProvider();
function firebaselogin() {
firebase.auth().signInWithRedirect(provider).then(function() {
return firebase.auth().getRedirectResult();
}).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
app.dialog.alert('Login success!! Welcome:' + result.user );
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
app.dialog.alert('Login error!! error:' + errorMessage );
});
}
When I run the app I get this error.
I have fixed that issue by just placing the firebase-app js to top.

Retrieve firebase data to web

// Initialize Firebase
var config = {
apiKey: "AIzaSyBz13eirmEOGD1uXOZwf6tKGnEsjfwsUFo",
authDomain: "platformtechproject.firebaseapp.com",
databaseURL: "https://platformtechproject.firebaseio.com",
projectId: "platformtechproject",
storageBucket: "platformtechproject.appspot.com",
messagingSenderId: "1065758005439"
};
firebase.initializeApp(config);
var database = firebase.database();
var msgRef = firebase.database().ref('survey');
//console.log(firebase);
var msgRef = firebase().ref('survey');
msgRef.on('value',gotData,errData);
I continue getting this error [Uncaught TypeError: firebase is not a function] as i am trying to read firebase data to web.
Chrome console error
here's how your code must be:
<script src="https://www.gstatic.com/firebasejs/4.8.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyBz13eirmEOGD1uXOZwf6tKGnEsjfwsUFo",
authDomain: "platformtechproject.firebaseapp.com",
databaseURL: "https://platformtechproject.firebaseio.com",
projectId: "platformtechproject",
storageBucket: "platformtechproject.appspot.com",
messagingSenderId: "1065758005439"
};
firebase.initializeApp(config);
var database = firebase.database();
var msgRef = database.ref('survey');
msgRef.on("child_added",function(snapshot) {
var changedPost = snapshot.val();
console.log(changedPost)
});
</script>
The code above works as you expect:
Note that msgRef listens on these predefined "events".
Details here: Read Event Types
Regards
Change this:
var database = firebase.database();
var msgRef = firebase.database().ref('survey');
//console.log(firebase);
var msgRef = firebase().ref('survey');
msgRef.on('value',gotData,errData);
to this:
var database = firebase.database();
var msgRef = database.ref('survey');
msgRef.on('value', function(snapshot) {
//retrieve data
});

Categories