I'm not able to display the picture of a logged user with email/password inside an <img> tag. I could display correctly the email,uid and all the details but the picture. This is the code:
HTML:
<img id="user-image">
Js:
firebase.auth().onAuthStateChanged(function(user) {
var userId = firebase.auth().currentUser;
var picture;
if (userId) {
picture = userId.photoURL;
document.getElementById("user-image").src = picture;
} else {
//Nothing;
}
});
When I go to the console I get error 404/null. Yes, the user Do have a picture ,I tried already with the exact path of the image file and it works.
Thanks.
Why do you call firebase.auth().currentUser; when you already have the user as a parameter of the function that is triggered on change?
What do you get if you do as follows:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var picture = user.photoURL;
console.log(picture). // <- check in you console that you get the correct url
document.getElementById("user-image").src = picture;
} else {
//Nothing;
}
});
Related
I am making a chat application that is setting an avatar image and when i set a avatar image then in the user that is already register and persent in my db i.e. mongo
And am setting the image and here is the code of my function that will set the avatar image in my db
`
const setProfilePicture = async () =>{
if(selectedAvatar === undefined){
toast.error("Please select an Avatar", toastOptions)
}else{
const user = await JSON.parse(localStorage.getItem("chat-app-user"));
const {data} = await axios.post(`${setAvatarRoute}/${user._id}`,{
image:avatars[selectedAvatar],
});
if(data.isSet){
user.isAvatarImageSet = true;
user.avatarImage = data.image;
localStorage.setItem("chat-app-user", JSON.stringify(user));
navigate("/")
}else{
toast.error("Error setting avatar. Please try again", toastOptions)
}
}
}
`and here my console that raising the error on clicking the button
Button that has onClick event enter image description here
My problem is that on load of my page, I need to access the information firebase.auth.currentUser, but this information is undefined if I call my function in the eventListener('load). But if I call it on click on a button, here the "add" button, (so a few seconds after page loaded), then it is working.
Here is what I tried in my code.
var FIREBASE_AUTH;
var FIREBASE_DATABASE;
const addButton = document.getElementById("add");
addButton.addEventListener("click", getEtablissemennts);
window.addEventListener('load', (event) => {
FIREBASE_AUTH = firebase.auth();
FIREBASE_DATABASE = firebase.database();
getEtablissemennts();
});
function getEtablissemennts(){
//works only if function is call on click on the button, doesn't work on load of the page
FIREBASE_DATABASE.ref('users').orderByChild('email').equalTo(FIREBASE_AUTH.currentUser.email).once("value", function(snapshot) {
...
}
}
You can't expect Firebase to authenticate the user and get their data on load. You should set up a listener:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is available now
} else {
// No user is signed in.
}
});
Source: https://firebase.google.com/docs/auth/web/manage-users#get_the_currently_signed-in_user
what i need
i need to show image when user select particular event. consider add to favorite functionality.
when user click on image data is store in array.
then user click particular image ,after reloading page another image should be shown at that position.
js code
on dom ready
show image on particular clicked div.
$(document).ready(function() {
console.log(localStorage);
if (localStorage.id!='')
{
var image_url='/images/star1_phonehover.png';
$('.favourate_dextop').css('background-image', 'url("' + image_url + '")');
}
});
js code to set and get items
function favaorite(sess_id,name,city,country,event_url,pointer)
{
/* clear storage code*/
//window.localStorage.clear();
/* store imageurl in localstorage */
var imageUrl='/images/star1_phonehover.png';
// Save data to the current local store//
if (typeof(localStorage) == 'undefined' ) {
console.log('Your browser does not support HTML5 localStorage. Try upgrading.');
}
else
{
try {
// Put the object into storage
localStorage.setItem('id' ,JSON.stringify(sess_id));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!');//data wasn't successfully saved due to quota exceed so throw an error
}
}
try {
// Put the object into storage
localStorage.setItem('name' ,JSON.stringify(name));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!');//data wasn't successfully saved due to quota exceed so throw an error
}
}
try {
// Put the object into storage
localStorage.setItem('city',JSON.stringify(city));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
try
{
// Put the object into storage
localStorage.setItem('country',JSON.stringify(country));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
try
{
// Put the object into storage
localStorage.setItem('event_url',JSON.stringify(event_url));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
try
{
// Put the object into storage
localStorage.setItem('imageUrl',JSON.stringify(imageUrl));
}
catch (e)
{
if (e == QUOTA_EXCEEDED_ERR)
{
console.log('Quota exceeded!'); //data wasn't successfully saved due to quota exceed so throw an error
}
}
}
/* fetch the data using from localstorage */
var id= [];
var name= [];
var city = [];
var country =[];
var event_url= [];
// Retrieve the object from storage
//var id, city, country,event_url;
var id = localStorage.getItem('id');
id = JSON.parse(id);
console.log(id);
var name = localStorage.getItem('name');
name = JSON.parse(name);
console.log(name);
var name = localStorage.getItem('name');
name = JSON.parse(name);
var city = localStorage.getItem('city');
city = JSON.parse(city);
console.log(city);
var country = localStorage.getItem('country');
country = JSON.parse(country);
console.log(country);
var event_url = localStorage.getItem('event_url');
event_url = JSON.parse(event_url);
///console.log(event_url);
var image_url = localStorage.getItem('imageUrl');
//event_url = JSON.parse(event_url);
alert(image_url);
//console.log(image_url);
//console.log($(pointer).closest('.evt_date').find('.star'));
if (id!='' )
{
$(pointer).closest('.evt_date').find('.favourate_dextop').css('background-image', 'url("' + imageUrl + '")');
$('.favourate_dextop').css('background-image', 'url("' + image_url + '")');
}
}
Problem
i have stored image in localstorage and trying load image on page refresh so ist applying on all div which div i have not clciked marke as favorite.
here is snapshot of json data:
in snapshot you could see localstorage only stores single json.
i need to ask is localstorage don"t store whole data that i have clicked its hows recent data in localstorage.
output should be
select particular data and store in localstorage in nested json string.
and on dom load or page refresh show particular on div whose id stored in localstorage.
i have tried a solution
$(document).ready(function() {
console.log(localStorage.id);
if (localStorage.id==30301)
{
var image_url='/images/star1_phonehover.png';
$('.favourate_dextop').css('background-image', 'url("' + image_url + '")');
}
});
then also it is applying image on all divs though it should apply on particular saved it of localstorage.
It sounds like you're trying to show a 'star' next to items a user has 'favorited' and you want to store these favorites in local storage.
Ignoring your existing code, I'd use a strategy like this:
1) Save the id's for each favorited item into an array and store that in local storage
localStorage.setItem('favorites' ,JSON.stringify(arrayOfFavorites));
2) On dom ready, add an attribute to all the 'favorited' items. Note, to do this you'll need to add some identifying attribute to each dom node you care about. I assume you have something like <div class='item' data-id='your-id'></div>:
var list = getArrayFromLocalStorage('favorites');
list.forEach(function(id) {
$('.item[data-id="' + id + '"').attr('favorite', '');
}
3) Finally, in your css, enable the background image for all items with the favorite attribute
item[favorite] {
background-image: '/images/star1_phonehover.png'
}
Hopefully this strategy points you in the right direction.
I'm trying to figure out how to use PhantomJS. I wrote the script below to try and automate posting a Facebook status. As far as I'm aware, the script isn't even logging in, which I'm unsure why. My code is below:
var page = require('webpage').create();
page.open('https://www.facebook.com/', function() {
page.includeJs("//code.jquery.com/jquery-1.11.0.min.js", function() {
page.evaluate(function() {
// Login
$('#email').val('email_here'); // Set email
$('#pass').val('password_here'); // Set PW
$('#u_0_4').click();
// Set status
$('#u_0_1p').val('123');
$('#u_0_1f').submit();
});
phantom.exit()
});
});
I'm not sure why the script won't work, or even to get some sort of error message output so I can figure out why my script isn't working.
Here is code for Loging in facebook i have written this in javascript it login's and takes a screen shot of your facebook home page..
var page = require('webpage').create();
var fillLoginInfo = function(){
var frm = document.getElementById("login_form");
frm.elements["email"].value = 'your fb email/username';
frm.elements["pass"].value = 'password';
frm.submit();
}
page.onLoadFinished = function(){
if(page.title == "Welcome to Facebook - Log In, Sign Up or Learn More"){
page.evaluate(fillLoginInfo);
return;
}
else
page.render('./screens/some.png');
console.log("completed");
phantom.exit();
}
page.open('https://www.facebook.com/');
Find this on Github: https://github.com/manishjo/Automation/blob/master/facebook_automation/fbScreenshot.js
Still trying to find out after login how to Post msg.
Thanks,
Manish Joshi
I'm facing an issue when calling FB.login when page on load, the FB.login pop up is block by the browser. Currently I know I've to call FB.login after a user click event but I've to do it this way due to the business logic from client.
FB.api('/me/permissions', function(response2) {
var permsArray = response2.data[0];
var permsNeeded = ["user_events"];
var permsToPrompt = [];
for (var i in permsNeeded) {
if (permsArray[permsNeeded[i]] == null) {
permsToPrompt.push(permsNeeded[i]);
}
}
if (permsToPrompt.length > 0) {
promptForPerms(permsToPrompt);
}
});
var promptForPerms = function(perms) {
FB.login(function(response) {
}, {scope: perms.join(',')});
};
Is there any solution to call FB.login() without user click event? Or is there any tweak for this? Appreciate for the help.
You're not going to be able to code your way around the popup blocker, unfortunately.
The way to solve this is by redirecting the user to the Facebook permissions dialog when the page loads as described in the docs for manually building a login flow.
You first need to detect if the user is authenticated / connected with your application already and only redirect if they are not connected. This is best done in the window.fbAsyncInit function like this:
window.fbAsyncInit = function() {
var myAppID = 'YOUR APPLICATION ID';
FB.init({ appId: myAppID });
FB.getLoginStatus(function(response) {
if ('connected' != response.status) {
window.location.href = 'https://www.facebook.com/dialog/oauth' +
'?client_id=' + myAppID +
'&scope=user_events' +
'&redirect_uri=' + encodeURIComponent(document.URL);
} else {
alert('welcome to my app');
}
});
};
The other option is to adjust your user journey slightly; perhaps if the user is not connected then you could display an overlay with a message asking them to authenticate and a button which when clicked calls FB.login.