Facebook login event subscribe doesn't work - javascript

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

Related

Facebook Javascript API keeps reconnecting [closed]

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!

Firing Dailymotion change events

I have a very basic question, I have the following code, I basically just trying to login to dailymotion.
window.dmAsyncInit = function()
{
DM.init({apiKey: 'MyAppID', status: true, cookie: true});
console.log('sdk loaded');
};
DM.Event.subscribe('auth.login', function(response)
{
// do something with response
if (response.status == 'connected')
{
console.log('connected');
testAPI();
}
else
{
DM.login(function(response)
{
if (response.session)
{
if (response.session.scope)
{
// user is logged in and granted some permissions.
// perms is a comma separated list of granted permissions
}
else
{
// user is logged in, but did not grant any permissions
}
}
else
{
// user is not logged in
}
}, {scope: 'read write'});
}
});
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol + '//api.dmcdn.net/all.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(e, s);
}());
function testAPI() {
DM.api('/user/rs', {fields: "screenname"}, function(response)
{
alert('Name is ' + response.screename);
});
}
I have subscribed to auth.login, but I am not sure how I fire up this event. I want to create a login button for dailymotion and bind this event to the button. How can I do this?
You have to create a button which will fire a login function on the "onclick" event.
How to login is described at http://www.dailymotion.com/doc/api/sdk-javascript.html#sdk-javascript-method-login
Basically, you call the DM.login function, which will prompt the user to login (a pop-up window will appear for the user to log in).

Don't load until function finishes loading

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.
}
}

FB.login not calling callback if cancel is selected

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

Issue with logout button

I'm trying to implement Facebook Connect login on my web page, and below you have my (poor) try so far.
If being logged out the login button is shown, as supposed.
If clicking the login button the Facebook login popup window appears, as supposed.
If loggin in the popup window disappears, the user gets logged in and the button changes to a logout button.
If clicking the logout button the user gets logged out, BUT!:
The button doesn't get changed to a login button.
Sometimes up to three popup windows (login) opens up.
The function testAPI() gets executed.
Sometimes the following error message is shown in the console: "Refused to display document because display forbidden by X-Frame-Options."
JS:
window.fbAsyncInit = function() {
FB.init({
appId : 'xxxxxxxxxxxxxxxx', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
showLogoutButton();
} else if (response.status === 'not_authorized') {
showLoginButton();
} else {
showLoginButton();
}
});
};
function showLoginButton() {
$('#FBButtonDiv').show();
$('#FBButton').html('Log in Facebook');
$('#FBButton').on('click', function(){
login();
});
}
function showLogoutButton() {
$('#FBButtonDiv').show();
$('#FBButton').html('Log out Facebook');
$('#FBButton').on('click', function(){
logout();
});
}
function login() {
FB.login(function(response) {
if (response.authResponse) {
// connected
testAPI();
showLogoutButton();
} else {
// cancelled
}
});
}
function logout() {
FB.logout(function(response) {
showLogoutButton();
});
}
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
(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));
HTML:
...
<div id="FBButtonDiv"><button id="FBButton">Facebook login!</button></div>
...
CSS:
#FBButtonDiv {
display: none;
}
So, what can be wrong in my code?
Note: I know the code contains of alot of DRY but I'll do alot of refactoring when I get it to work.
Not particularly my speciality, JS/FB-API but I would guess:
function logout() {
FB.logout(function(response) {
showLogoutButton();
});
}
Should be:
function logout() {
FB.logout(function(response) {
showLoginButton();
});
}
Because after the response is recieved, the callback should be to show the login button to the now logged out user. Of course you should probably check the response similarly to login to confirm the logout was succesful.

Categories