Firebase Authentication works but keeps on refreshing the page - javascript
So I am new to web development and Firebase as well. I have been trying to build a multi page web app in simple javascript and firebase. App looks good and works for most of the part. Yet it is really of no use as I am having following issue :
When I sign in through googleAuthProvider (on my index.html page), I am taken to another page which is main.html . Now til here is fine. But once the main.html is loaded, it goes into a loop of continuous refreshing.
My rationale behind this is, that somehow Firebase is trying to re-authenticate the page on loading. And so the loop happens. But why, this I am not able to debug.
I have looked over almost everything I could find on internet but no where I could find a solution which is for simple javascript based multi page web app with firebase.
Here's a link to my app if anyone is interested and kind enough to have a look.
Chatbot
Also, here is my javascript code too.
var config = {
apiKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXX.firebaseapp.com",
databaseURL: "https://XXXXXXXX.firebaseio.com",
projectId: "XXXXXXXXXX",
storageBucket: "XXXXXXXXXX.appspot.com",
messagingSenderId: "XXXXXXXXXXXX"
};
firebase.initializeApp(config);
//===============================================================================================
$("document").ready(function(){
const signinGoogle = document.getElementById("googleAuth");
const signOut = document.getElementById("signout");
const sendMsg = document.getElementById("send");
const messageBox = document.getElementById("chatBox");
const displayNAME = document.getElementById("dipslayName");
const storageRef = firebase.storage().ref();
var currentUser;
var name;
var photoUrl;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
initApp();
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(signinGoogle){
googleAuth.addEventListener('click', e=>{
firebase.auth().signInWithPopup(new firebase.auth.GoogleAuthProvider()).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var tokenGoogle = result.credential.accessToken;
// The signed-in user info.
var userGoogle = result.user;
// ...Below line to be rmeooved if not working expectedly.
// var user = firebase.auth().currentUser;
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
if(signOut){
signout.addEventListener('click', e=>{
if(confirm("Do you wish to leave?")){
promise = firebase.auth().signOut().then(function(){
window.location = "index.html";
});
promise.catch(e =>
console.log(e.message))
}
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
function initApp(){
firebase.auth().onAuthStateChanged(function(user){
if(user){
window.location = "main.html";
$("document").ready(function(){
currentUser = firebase.auth().currentUser;
name = currentUser.displayName;
photoUrl = currentUser.photoURL ;
console.log("Current user's name is : "+name);
console.log("Current user's photoUrl is : "+photoUrl);
displayNAME.innerHTML = "Hi "+name;
//+++++++++++Retrieving Msgs++++++++++++++++++++++++++++++++
var i=1;
var firebaseRetrieveRef = firebase.database().ref().child(name+uid+"/MessageBoard");
firebaseRetrieveRef.on("child_added", snap =>{
var retrievedMsg = snap.val();
console.log("retrieved msgs is : "+retrievedMsg);
$("#taskList").append("<li id='list"+i+"'><div style='width:100%'><img src='"+photoUrl+"'style='width:10px;height:10px;border-radius:5px;'/><label>"+name+"</label></div><div style='width:100%'><p>"+retrievedMsg+"</p></div></li>");
i++;
});
//+++++++++++Storing Msgs++++++++++++++++++++++++++++++++
$("#send").on("click", function(){
var newMessage=messageBox.value;
if(newMessage==""){
alert("Empty Message doesn't make any sense, does it?? ");
}
else{
var firebaseStoreRef = firebase.database().ref().child(name+uid+"/MessageBoard");
firebaseStoreRef.push().set(newMessage);
messageBox.value="";
}
});
//+++++++++++Clearing/deleting all tasks++++++++++++++++++++++++
$("#clear").on("click", function(){
var firebaseDeleteRef = firebase.database().ref().child(name+uid+"/MessageBoard");
firebaseDeleteRef.remove();
$( ".scrolls" ).empty();
});
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++
});
}
else
{
console.log(user+" is not logged in");
}
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
});
You keep redirecting to main.html.
firebase.auth().onAuthStateChanged(function(user){
if(user){
window.location = "main.html";
You keep redirecting to main.html whenever you determine the user is signed in. Make sure on main.html, you are not using the same logic and redirecting again.
Related
After making payment not able to redirect on relay url
I am making the payment using authorize.net weblink "https://test.authorize.net/gateway/transact.dll" on the sharepoint page. After filling in the information and making the payment it doest not redirect the page on x_relay_url. Instead, it shows the error of "Sorry something went wrong" as below. I tried to make the payment using sandbox account. it makes the payment transaction however after transaction it does not redirect on URL instead it shows the error. var fingerprint1; var amount1 = "95.00"; $(document).ready(function(){ }); function setFormAction(button) { var theForm = $(button).parents('form:first')[0]; //sandbox var loginid = "99NSdk8a" var txnkey = "9s54MPz333NcVUm5" //Randomize var sequence = parseInt(1000 * Math.random()); var tstamp = GetSecondsSince1970 () //added for student rate--CHANGE THIS TO USE VARIABLES SET AT PAGE LOAD if (theForm.student.checked) { amount1 = "0.05"; } else {amount1 = "95.00"} // set form action if (theForm.payment_type[0].checked){ //theForm.action = "https://secure.authorize.net/gateway/transact.dll"; theForm.action = "https://test.authorize.net/gateway/transact.dll"; theForm.method="POST" } else { theForm.action = "http://trainingcenter.umaryland.edu/SaveRegistrations/save_registrationSuicidePrevention2019.aspx"; } // set amount and fingerprint theForm.x_amount.value = amount1; theForm.x_fp_hash.value = fingerprint1; theForm.submit(); return (true); }
Insecure connection error with firebase deployment
Actually, I deployed a website through Firebase and it was successful. Then there was nothing in the website .the website is www.novusorg.com The website is just about the organization. But now I added a registration form for the website. The registration form in HTML with ids is connected with JavaScript. And I deployed it again. But now when I try to open the website it says insecure connection. Please help me with the error. EMERGENCY THANK YOU IN ADVANCE website: www.novusorg.com var config = { apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", authDomain: "novuxxxxxxxxxxxx.firebaseapp.com", databaseURL: "https://novusxxxxxxxxxxxxx.firebaseio.com", projectId: "novxxxxxxxxxxxxxx", storageBucket: "", messagingSenderId: "xxxxxxxxxxxx" }; firebase.initializeApp(config); //reference messages collection var messagesRef = firebase.database().ref('messages'); document.getElementById('registrationform1').addEventListener('submit',submitform); function submitform(e) { e.preventDefault(); var regname = getInputVal('regname'); var regmail = getInputVal('regmail'); var regregnum = getInputVal('regregnum'); var regnumber = getInputVal('regnumber'); var regcourse = getInputVal('regcourse'); var regreason = getInputVal('regreason'); var regfd= getInputVal('regfd'); var regbd = getInputVal('regbd'); var regad = getInputVal('regad'); var regiod = getInputVal('regiod'); var reguxd = getInputVal('reguxd'); var regpty = getInputVal('regpty'); var reggfd = getInputVal('reggfd'); var regved = getInputVal('regved'); var regfa = getInputVal('regfa'); var regcw = getInputVal('regcw'); var regmt = getInputVal('regmt'); var regem = getInputVal('regem'); saveMessage(regname,regmail,regregnum,regnumber,regcourse,regreason,regfd,regbd,regad,regiod,reguxd,regpty,reggfd,regved,regfa,regcw,regmt,regem); document.querySelector('.regalert').style.display='block'; setTimeout(function(){ document.querySelector('.regalert').style.display='none'; },3000); document.getElementById('registrationform1').reset(); } function getInputVal(id) { return document.getElementById(id).value; } function saveMessage(regname,regmail,regregnum,regnumber,regcourse,regreason,regfd,regbd , regad,regiod,reguxd,regpty,reggfd,regved,regfa,regcw,regmt,regem) { var newMessageRef = messagesRef.push(); newMessageRef.set({ regname:regname, regmail:regmail, regregnum:regregnum, regnumber:regnumber, regcourse:regcourse, regreason:regreason, regfd:regfd, regbd:regbd, regad:regad, regiod:regiod, reguxd:reguxd, regpty:regpty, reggfd:reggfd, regved:regved, regfa:regfa, regcw:regcw, regmt:regmt, regem:regem }); }
I don't see your landing page on the website, I instead see a Google Docs page.
Data retrieval query for firebase not working
Above is the db structure and below is the code to retrieve the data from firebase database, I am unable to get the data from my db.I need help in retrieving the data from my firebase db.I have attached the database image for the view of my db. function check(userId,snapcity){ var rootRef=firebase.database().ref().child('users'); rootRef.on('child_added', function(snap){ if(snap.child("userId").val()==userId){ snapcity=snap.child("city").val(); } }); console.log(snapcity); console.log(ajaxData.geoplugin_city); if(snapcity){ if(snapcity!=ajaxData.geoplugin_city){ logout(); alert("you can't login because previously you were logged from "+snapcity ); } } } firebase.auth().onAuthStateChanged(function(user) { if (user) { // User is signed in. userId=user.uid; //alert(userId); var date = new Date(); var n = date.toDateString(); var time = date.toLocaleTimeString(); datetime=n+" "+time; snapcity=""; check(userId,snapcity); var database = firebase.database(); writeUserData(userId,ajaxData.geoplugin_request,ajaxData.geoplugin_city,datetime); document.getElementById("user_div").style.display = "block"; document.getElementById("login_div").style.display = "none"; var user = firebase.auth().currentUser; if(user != null){ var email_id = user.email; document.getElementById("user_para").innerHTML = "Welcome User : " + email_id; console.log('data'); console.log(ajaxData); html="<p>ip: "+ajaxData.geoplugin_request+"</p><p>Country Code: +44</p><p>Country: "+ajaxData.geoplugin_countryName+"</p><p>Country Abbrevation: "+ajaxData.geoplugin_countryCode+"</p><p>Region Code: "+ajaxData.geoplugin_regionCode+"</p><p>Region Name: "+ajaxData.geoplugin_regionName+"</p><p>City: "+ajaxData.geoplugin_city+"</p><p>Time Zone: "+ajaxData.geoplugin_timezone+"</p><p>Latitude: "+ajaxData.geoplugin_latitude+"</p><p>Longitude: "+ajaxData.geoplugin_longitude+"</p><p>Last Login: "+datetime+"</p>"; $('#data').html(html); } } else { // No user is signed in. document.getElementById("user_div").style.display = "none"; document.getElementById("login_div").style.display = "block"; } }); [1]: https://i.stack.imgur.com/JVeRD.jpg
This: rootRef.on('child_added', function(snap){ if(snap.child("userId").val()==userId){ snapcity=snap.child("city").val(); } }); Can be replaces by: rootRef.child(userId).once('value', function(snap){ snapcity = snap.child("city").val(); }); Next you need to move all code that needs snapcity into the callback function. So: rootRef.child(userId).once('value', function(snap){ snapcity = snap.child("city").val(); console.log(snapcity, ajaxData.geoplugin_city); if(snapcity){ if(snapcity!=ajaxData.geoplugin_city){ logout(); alert("you can't login because previously you were logged from: "+snapcity ); } } });
Firebase and crossroads user profile
how can I make a router system with crossroads.js where if I go to for example this URL: localhost/user/{{username}} then get the details of that user there's entered in the URL with firebase.
get user detail once : var database = firebase.database(); var route1 = crossroads.addRoute('/user/{username}', function(id){ firebase.database().ref('/user/' + id).once('value').then(function(snapshot) { var username = snapshot.val().username; // ... }); });
How to use onUrlChanged?
I'm trying to log in into gmail account using javascript, and I have a problem: after I insert my email and press 'next', the page redirect me to new url asking for my password. my question is, How can I monitor the current url and know when it changes? Im trying to use page.onUrlChanged but it doesn't work test.open(url, function(status) { test.page.evaluate(function (email, password) { document.getElementById('Email').value = email; document.getElementById('next').click(); test.page.onUrlChanged = function(targetUrl) { console.log(targetUrl); } }, email, password);});
you can use phatomjs for log URL change..below is simple code for that var webPage = require('webpage'); var page = webPage.create(); page.onUrlChanged = function(targetUrl) { console.log('New URL: ' + targetUrl); }; find more about phantomjs http://phantomjs.org/api/webpage/handler/on-url-changed.html or You can use window.onblur = function() { console.log('blur'); }