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!
Related
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
In my web platform I show a Facebook likebox to users.
I need to know when a user log in on Facebook after clicking the like button of the likebox.
I tried to do so by using the FB.Event.subscribe function on events auth.statusChange and auth.authResponseChange (suggested in documentation), but without success.
This is an example of the code I use:
/* Just to wait facebook functions are ready */
var handle = setInterval(function() {
if(typeof(FB) != 'undefined'){
fbReady();
clearInterval(handle);
}
}, 1000);
/* Get connection status */
function fbReady() {
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
status == "connected";
} else if (response.status === 'not_authorized') {
status == "not_authorized";
} else {
status == "unknown";
}
/* I don't use status yet */
setSubscriptions(status);
});
}
/* set event listeners for login and liked */
function setSubscriptions(status){
/* Like event subscription */
FB.Event.subscribe('edge.create',
function(response) {
alert('user liked the page');
});
/* status change event subscription */
FB.Event.subscribe('auth.statusChange',
function(response) {
alert('user status is changed in:' + response.status);
});
/* auth response change event subscription */
FB.Event.subscribe('auth.authResponseChange',
function(response) {
alert('user auth response is changed in:' + response.status);
});
}
Only edge.create event fires the related callback when the like button is pressed, but nothing happen when a user log in.
The situation does not change if the user which log in has status connected (he accepted my App in facebook settings) or not_authorized.
I tried to supply a JsFiddle with an interactive code but Facebook js sdk doesn't work that way.
Thanks in advance for your help
I have the following problem:
Once the user is logged in facebook if I run the following code:
FB.api('/me', function(user) {
alert(user.name);
});
It pops up an alert with "Udefined" written.
But if I change the code in the following way:
FB.api( /[MY_REAL_FACEBOOK_ID], function(user) {
alert(user.name);
});
It response in the correct manner.
How it is possible ?
Why '/me' never works ?
I think you might be querying "/me" in context of the app rather than the user. The documentation is not as explicit as it could be, but I've had the same issue.
Are you able to use FB.getLoginStatus?
After I have FB.init set up, I make a call to FB.getLoginStatus similar to what is found below. There might be a better way on how to do this, but it works for me.
Hopefully this helps:
FB.getLoginStatus(function (response) {
if (response.session) {
// logged in and connected user, someone you know
graphUrl = "https://graph.facebook.com/me?access_token=" + response.session.access_token + "&callback=displayUser"
var script = document.createElement("script");
script.src = graphUrl;
document.body.appendChild(script);
} else {
// no user session available, someone you dont know
}});
function displayUser(user) {
alert(user.name);
}
Use the below code to overcome the Undefined problem:
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : your_app_id,
status : true,
xfbml : true
});
// Additional initialization code such as adding Event Listeners goes here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert("connected");
connecter=true;
FB.api('/me', function(user) {
alert(user.name);
alert(user.first_name);
alert(user.last_name);
alert(user.email);
});
}
});