I am using Facebook API to log in a user. It logs in a user successfully.
But whenever I refresh the website or close it then reopen it logs out automatically. I don't need that I want a user logged in until he himself logs out of my website. How do I do it?
This is my code:
function statusChangeCallback(response) {
if (response.status === 'connected') {
setElements(true);
console.log('Logged in');
instaInfo();
} else {
setElements(false);
console.log('not logged in');
}
}
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
function setElements(isLoggedIn) {
if (isLoggedIn) {
document.querySelector('#fb-btn').style.display = 'none';
document.querySelector('.logout').style.display = 'block';
document.querySelector('.navigation').style.display = 'block';
document.querySelector('.nav-main').style.visibility = 'visible';
document.querySelector('#container').style.display = 'block';
} else {
document.querySelector('#fb-btn').style.display = 'block';
document.querySelector('.logout').style.display = 'none';
document.querySelector('.navigation').style.display = 'none';
document.querySelector('.nav-main').style.visibility = 'hidden';
document.querySelector('#container').style.display = 'none';
}
}
document.querySelector('.logout').addEventListener('click', () => {
FB.logout(function() {
setElements(false);
console.log('Logged Out!');
});
});
According to the facebook documentation:
While you can call FB.getLoginStatus any time (for example, when the
user tries to take a social action), most social apps need to know the
user's status as soon as possible after the page loads. In this case,
rather than calling FB.getLoginStatus explicitly, it is possible to
check the user's status by setting status: true when you call FB.init.
To receive the response of this call, you must subscribe to the
auth.statusChange event. The response object passed by this event is
identical to that which would be returned by calling FB.getLoginStatus
explicitly.
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
It might just be that you're running into a problem with the asynchronous nature of javascript in your code example. Have you checked what your call on getLoginStatus actually returns?
You can take advantage of the browser's localStorage (it' s a method of the window object) to keep the data even after reloading the page or even after closing the window.
Take a look here: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Related
I have a series of buttons that execute different functions when clicked. The function checks whether the user is logged in, and if so proceeds, if not it displays an overlay with ability to log in/create account.
What I want to do is re-execute the button click after log-in, without the user having to reclick it.
I have it working at the moment, but I'm pretty sure that what I'm doing isn't best practice, so looking for advice on how I can improve...
Here's what I'm doing: setting a global variable "pending_request" that stores the function to be re-run and in the success part of the log-in ajax request calling "eval(pending_request)"
Example of one of the buttons:
jQuery('#maybe_button').click(function() {
pending_request = "jQuery('#maybe_button').click()"
var loggedin = get_login_status();
if (loggedin == true) {
rec_status("maybe");
}
});
.
success: function(data) {
if(data === "User not found"){
alert("Email or Password incorrect, please try again");
}else{
document.getElementById('loginscreen').style.display = 'none';
document.getElementById('locationover').style.display = 'none';
eval(pending_request);
pending_request = "";
}
}
Register a function to handle the click and then invoke that func directly without eval().
jQuery('#maybe_button').on('click', myFunction)
This executes myFunction when the button is clicked. Now you can "re-run" the function code every time you need it with myFunction().
And btw since you are using jQuery you can do $('#loginscreen').hide() where $ is an alias for jQuery that's auto defined.
EDIT
Please, take a look at the following code:
var pressedButton = null;
$('button1').on('click', function() {
if (!isLoggedIn()) {
pressedButton = $(this);
return;
}
// ...
});
And, in your success handler:
success: function() {
// ...
if (pressedButton) pressedButton.trigger('click');
// ...
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm building a site which, when the user connects to Facebook, appends a profile picture to a div, amongst other things. When I leave the site open for a while and come back, I see that the same profile picture has been appended multiple times, so clearly the Facebook connection closes and reopens every so often.
Is there any way to stop this?
Thanks
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '219892158204692',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
// for any authentication related change, such as login, logout or session refresh. This means that
// whenever someone who was previously logged out tries to log in again, the correct case below
// will be handled.
FB.Event.subscribe('auth.authResponseChange', function(response) {
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected') {
fbconnect = true;
$('#fbloginbutton').hide();
$('#friendcontainer').append('<span id="loader"><center>Loading...</center></span>');
// The response object is returned with a status field that lets the app know the current
// login status of the person. In this case, we're handling the situation where they
// have logged in to the app.
FB.api(
"/me",
function (response) {
if (response && !response.error) {
fbid = response['id'];
user['id'] = response['id'];
getuserhighscore(user['id']);
userpercentile(parseInt(user['highscore']));
$('#statscontainer').append('<span class="label">Highest Score</span>: '+user['highscore']+'<br>');
$('#statscontainer').append('<span class="label">Percentile (global)</span>: '+user['percentile']+'<br>');
drawuserchart(user['id']);
}
}
);
FB.api(
"/fql?q=select%20uid%2C%20first_name%2C%20is_app_user%20from%20user%20where%20uid%20in%20(select%20uid2%20from%20friend%20where%20uid1%3Dme())%20and%20is_app_user%3D1",
function (response) {
console.log('friends installed:');
console.log(response);
console.log(response['data'][0].id);
var responseArray = [];
responseArray.push(response);
console.log(responseArray);
user['friends'] = response['data'].length;
if (response && !response.error) {
for (var i=0;i<response['data'].length;i++){
friend = response['data'][i];
console.log('friend coming up');
console.log(friend);
friends.push(friend.uid);
$('#friendcontainer').append('<div class="friendbox" id="'+friend.uid+'"></div>');
$('#'+friend.uid+'').append('<img class="friendpic" src="https://graph.facebook.com/'+friend.uid+'/picture?height=60&width=60&type=square">');
$('#'+friend.uid+'').append('<div class="friendname">'+friend.first_name+'</div>');
gethighscore(friend.uid);
$('#'+friend.uid+'').append(' - '+friendscores[i]+'');
console.log(friendscores);
}
$('#loader').remove();
user['friendrank'] = 1;
for (var i=0;i<friendscores.length;i++){
if(friendscores[i] > user['highscore']){
user['friendrank']++;
}
}
$('#statscontainer').append('<span class="label">Rank (among friends)</span>: '+user['friendrank']+'<br>');
} else {
console.log(response.error)
}
}
);
console.log(friends);
console.log(user)
FB.api(
"/me/picture",
{
"redirect": false,
"height": "100",
"type": "normal",
"width": "100"
},
function (response) {
if (response && !response.error) {
user['picture'] = response['data']['url'];
console.log(user['picture']);
$('#thumbnail').append('<img id="thumbnailpic" src="'+user['picture']+'">');
}
}
);
testAPI();
} else if (response.status === 'not_authorized') {
// In this case, the person is logged into Facebook, but not into the app, so we call
// FB.login() to prompt them to do so.
// In real-life usage, you wouldn't want to immediately prompt someone to login
// like this, for two reasons:
// (1) JavaScript created popup windows are blocked by most browsers unless they
// result from direct interaction from people using the app (such as a mouse click)
// (2) it is a bad experience to be continually prompted to login upon page load.
FB.login();
} else {
// In this case, the person is not logged into Facebook, so we call the login()
// function to prompt them to do so. Note that at this stage there is no indication
// of whether they are logged into the app. If they aren't then they'll see the Login
// dialog right after they log in to Facebook.
// The same caveats as above apply to the FB.login() call here.
FB.login();
}
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
// Here we run a very simple test of the Graph API after login is successful.
// This testAPI() function is only called in those cases.
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
$('#sidebar').slideDown("slow");
});
}
</script>
FB.Event.subscribe on auth.authResponseChange is triggered whenever there's change in the auth. A user session is maintained for some minutes, so what's happening is the event is triggered after sometime and the photos are appended again.
You should not write this whole code in this event block.
So, if you want to do this all in this same page, what you can do is, maintain a bool, say bool isLoaded=false;, now when your call is completed: isLoaded=true; indicating that the data is loaded.
And make your API calls whenever it is false, just like this-
if (response.status === 'connected') {
if(isLoaded){
fbconnect = true;
....
....
}
else
// dont do anything
}
Hope that helps!
I am struggling with this issue for a couple of hours, but no sign of success. I am trying to implement the facebook login. this is my code:
function fblogin() {
FB.login(function(response) {
if (response.authResponse) {
var url = '/me?fields=name,email';
FB.api(url, function(response) {
$('#email_login').val(response.email);
$('#pwd_login').val(response.name);
$('#sess_id').val(response.id);
if($('#evil_username').val()==""){
$('#loginform').submit();
}else{
// doh you are bot
}
});
} else {
// cancelled
}
}, {scope:'email'});
}
but once i click facebook login button, i am getting too much recursion in console. why is that? i read lots of problems here in stackoverflow regarding this issue, but couldnot find the clue for my case.
i dont have recursion here, but what is happening which causes that recursion?
and there is a call for it from
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxx',
channelUrl : '//www.mydomain.de/channel.html',
status : true,
cookie : true,
xfbml : true
});
// Additional init code here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// connected
} else if (response.status === 'not_authorized') {
// not_authorized
fblogin();
} else {
// not_logged_in
fblogin();
}
});
};
and also from normal LOGIN button which triggers the fblogin().
i don't see where your onclick code is or the action that calls fblogin() and i'm assuming the problem is when fblogin() gets called.
function fblogin(event) {
event.stopPropagation();
add an event parameter to each function fblogin(event) call so this can be cross browser compatible.
when an event occurs, it traverses to parent elements so they can inherit the event handler, in your case function fblogin(). when you stop propagation stopPropagation() you stop DOM traversing and the element that calls the function won't pass the handler to the parent if stopPropagation is set. that all means the browser will stop looping through all your DOM elements and making your jquery less recursive.
I'm pulling album photos from Facebook API and then arranging them in masonry style. I have it set up so that I'll run the API function, then when I click a button it'll run the masonry function, which works fine. Now what I want to do is have the masonry run automatically after all the images are downloaded, like so:
function fbAPI() {
//downloading photos and placing them in a div
masonryFunction();
}
function masonryFunction(){
//run the masonry plugin
}
The trouble I run into though is masonryFunction runs well before fbAPI has finished doing it's thing, which prevents it from working (all the photos must be loaded up first). Now I can't simply have masonryFunction run when the page is loaded because fbAPI doesn't get launched until after some user input. What can I do?
Call the fbAPI() function in the callback function for the FB login function.
For example,
FB.login(function(response) {
if (response.authResponse) {
facebookLoggedIn();
} else {
alert('User cancelled login or did not fully authorize.');
}
});
function facebookLoggedIn() {
fbAPI();
}
Or, subscribe to FB auth.statusChange event:
FB.Event.subscribe('auth.statusChange', function(response) {
facebookStatusChange(response);
});
function facebookStatusChange(response) {
if (response.status === 'connected') {
uid = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
facebookLoggedIn();
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
}
I'm trying to get the users permission if they haven't granted the publish_stream permission.
I have this function:
function AskPermission()
{
ResizeUnity(0);
FB.login(function(response)
{
alert("Hit");
if (response.authResponse)
{
alert('Granted!');
GetUnity().SendMessage("POST", "POST", "Granted");
}
else
{
alert('User cancelled login or did not fully authorize.');
GetUnity().SendMessage("POST", "POST", "");
}
ResizeUnity(1);
}, {scope: 'publish_stream'});
}
When it's called a small window pops up asking .... would like to access your public profile and friends list. There's 2 buttons Okay and cancel. When Okay is pressed it goes on to another screen asking .... would like to post to your friends on your behalf. Again 2 button, Okay and Skip.
When I press the first skip denying all permissions it doesn't return anything. the alert("Hit"); is not called.
When I do press Okay on the first prompt it goes on to the second popup and asks about the posting on behalf. I press Okay, the alert 'Granted' is called.
When I press skip the alert 'Granted' is also called even though I hit skip.
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized'){
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});
Use this Facebook function to check whether user grant permissions or not.
You can recall same function if user not permitted your app. For more assistance in code, I can help you. :)
For more information see :Fb.getLoginStatus
Maybe this is happening because you are trying to open Facebook login in a popup but it opens in the same window where you called fb.login. When you click Cancel, Facebook tries to close the window, but as it wasn't opened by facebook the window won't close. It never tries to follow the callback url.
Try using in the config {display: "touch"} or {display: "page"} like this:
function AskPermission()
{ResizeUnity(0);
FB.login(function(response)
{
alert("Hit");
if (response.authResponse)
{
alert('Granted!');
GetUnity().SendMessage("POST", "POST", "Granted");
}
else
{
alert('User cancelled login or did not fully authorize.');
GetUnity().SendMessage("POST", "POST", "");
}
ResizeUnity(1);
}, {scope: 'publish_stream', display: 'page'});
}
Is there a reason why not to ask for all the permissions to need in one screen itself. Howevern, keep in mind that as per facebook documentation, ask few permissions to begin with and then keep increasing the permissions request on the go.
https://developers.facebook.com/docs/reference/login/#permissions
Try this code
FB.login(function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: ''});
Hope that helps