check facebook session onload - javascript

Below I am trying to check the session of facebook on page load. And want to show different content on page as per login status. What's wrong?
I want first two check the user connection status. Then only appropriate content to be shown on the page.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
</head>
<body>
<script>
window.fbAsyncInit = function() {
// init the FB JS SDK
FB.init({
appId : '1781292862', // App ID from the app dashboard
// channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel file for x-domain comms
status : true, // Check Facebook Login status
xfbml : true // Look for social plugins on the page
});
// Additional initialization code such as adding Event Listeners goes here
};
window.onload(){
FB.init({
appId : '178812862', // Your FB app ID from www.facebook.com/developers/
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') {
alert("yes");
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
} else {
// the user isn't logged in to Facebook.
}
});
</script>
</body>
</html>

First, you'll want to use response.status instead of response.session. And since the status is going to be string either way ("connected", "not_authorized", or "unknown"), you'll want to set up your if statements accordingly. The following example is from https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
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.
}
});
Let me know if that makes sense, or if you have any questions :)
Update
Your script is still missing the little closure that loads the facebook sdk into your document (which is why you're getting the error that FB is not defined). Try replacing your whole script block with the following:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 1343434343, // Your FB app ID from www.facebook.com/developers/
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') {
alert("yes");
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
} else {
// the user isn't logged in to Facebook.
}
});
};
// Load the SDK asynchronously
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script>
(^That last part is what loads the facebook sdk.) Try it out and let me know how it goes :)

Try this
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(response) {
id= response.id;
if(id==undefined)
{
alert('I am logged out');
}
else
{
alert('I am logged in');
}
})
}
});

Related

How to redirect user after facebook login

I am developing a game which requires user to login and then uses the login details to update the leaderboard. But the problem is that after the user logs in, the login dialog does not get closed automatically and the user is not redirected to the game. Here is the code which is taken from here
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXXXXXXX',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.authResponseChange', function(response) {
shepResponse = response;
// Here we specify what we do with the response anytime this event occurs.
if (response.status === 'connected')
testAPI();
}
else if (response.status === 'not_authorized') {
FB.login();
} else {
FB.login();
}
});
};
(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 = "http://connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
}
try not wrapping FB.Event.subscribe and testAPI() inside the fbAsyncInit function.
Also try auth.statusChange instead of auth.authResponseChange
var fb_handleStatusChange = function(response) {
if (response.authResponse) {
// user logged in
} else {
// not logged in or logged out
}
}
FB.Event.subscribe('auth.statusChange', fb_handleStatusChange);
Also, i think that the login redirect should be to a page that has this code and is listening for status change. I would not redirect back to the same page as the one used for login.

Hosting Facebook apps on Dropbox

I'm trying to host a simple JS based Facebook app on dropbox following this question:
Server required for a Facebook application?
Currently I just want to get the login part done before I can continue but i'm having some issues - apparently the call for FB.getLoginStatus doesn't return so the actual login function isn't called.
If I call login() directly (currently commented out) I manage to log into Facebook but then the call FB.api('/me', function(response) {...}) doesn't return so I'm logged in but can't really do anything.
What am I missing? I've set the correct URLs in my Facebook's app page and I really don't know what I'm doing wrong, why does it have to be so hard? :/
Here is my JS code (pretty much copy+paste from Facebook login tutorial) and the HTML is exactly copy+paste from that tutorial.
// Additional JS functions here
function testAPI() {
document.write('Welcome! Fetching your information.... </br>');
FB.api('/me', function(response) {
document.write('Good to see you, ' + response.name + '.</br');
});
}
function login() {
document.write('Logging to Facebook </br>');
FB.login(function(response) {
if (response.authResponse) {
// connected
document.write("User now connected </br>");
testAPI();
} else {
// cancelled
document.write("User cancelled </br>");
}
});
}
window.fbAsyncInit = function() {
document.write("Connecting to facebook </br>");
FB.init({
appId : '542474505763387', // App ID
channelUrl : 'https://dl-web.dropbox.com/get/index.html?w=71a3a216', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
//login();
FB.getLoginStatus(function(response) {
document.write("Response </br>");
if (response.status === 'connected') {
// connected
document.write("connected </br>");
} else if (response.status === 'not_authorized') {
// not_authorized
document.write("not_authorized </br>");
login();
} else {
// not_logged_in
document.write("not_logged_in </br>");
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));
</script>

FB.getLoginStatus is not firing even the sandbox settings are off

I'm using the Facebook API in order to check if the user who visits my page is logged into Facebook or not. I tried everything, couldn't came up with a solution. I would like to especially state that sandbox mode is off. And my code is right below;
<div id="fb-root"></div>
<script>
function fbLoginStatus(response) {
console.log("Status: "+response.session);
if(response.session) {
//user is logged in, display profile div
alert("Logged in");
} else {
//user is not logged in, display guest div
alert("Not logged in");
}
}
window.fbAsyncInit = function() {
FB.init({
appId : '111111111111111', // Channel File
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){
console.log("Hey");
if(response.session){
console.log("You are logged in");
}
else{
console.log("You are not logged in");
}
});
// Additional initialization code here
};
// 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 = "http://connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
FB.getLoginStatus is the function that is used to detect if user is logged into FB or not. In the callback of function you are checking response.session but as per my understanding this session is not a valid attribute of returning JSON object. You should use response.status. So code will become like below.
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
alert("LOG IN");
} 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.
}
});
Hope this Helps
Kaushik

Detect if facebook user is logged in with no popups

I am trying to check if the user is logged in in facebook (and redirect to other page) but I can't open any popup for this:
This will work: but would open a popup in case the user is NOT logged in facebook
FB.login(function(response) {
if(response.status == 'connected')
/*Redirect here*/
});
This is working in another web of mine, but not here
window.fbAsyncInit = function() {
FB.init({
appId : myAppid, // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
FB.Event.subscribe('auth.login', function() {
/* REDIRECT HERE */
});
};
// 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/es_ES/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
Any clue here?
You can use FB.getLoginStatus to get the info you want.
The first time in the current browser session that FB.getLoginStatus is called, or the JS SDK is init'd with status: true, the response object will be cached by the SDK. Subsequent calls to FB.getLoginStatus will return data from this cached response.
Example from documentation:
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.
}
});

JavaScript SDK Facebook: Trouble With Init Script

Trying to figure out how to use the JavaScript SDK. I'm new to JavaScrip. I was able to use the PHP SDK but want to run my stuff clientside. Anyhoo, I don't really understand the SDK documentation on the develop site. So the base code is:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
Which I think I understand...it loads the SDK and then runs the FB.init stuff once it loads. I don't know where to put all of the OAuth stuff though, and how to structure the login request (i.e. if not logged in the make a button and if you are then return access token etc.
Can someone hold my hand through this beginning part. I've searched everywhere and I just don't quite get it.
Edit:
Okay, second try with authentication. Didn't work:
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXX', // App ID
channelUrl : 'XXX', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
// Additional initialization code here
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and connected to 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;
FB.api('/me', function(response) {
alert(response.name);
});
} else if (response.status === 'not_authorized') {
FB.login(function(response) {
if (response.authResponse) {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
FB.logout(function(response) {
console.log('Logged out.');
});
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});
} else {
}
})
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
Thanks!
Just below this line,
// Additional initialization code here
is where the oauth stuff goes.
I would suggest getting used to calling FB.getLoginStatus() first. See: http://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
EDIT
based upon the question edit above
This should be done inside the window.fbAsyncInit function
FB.api('/me', function(response) {
alert(response.name);
});
and only after you've checked the getLoginStatus() so you know if the person is logged in or not.

Categories