I'm trying to use the facebook javascript SDK to let my app connect to the user's facebook account.
Is there a simple way to check if my app is already connected to facebook before running the code to connect it? It has to reload the page so the user can actually see that they are logged in through facebook, but if I do location.reload(); at the end it will go into an infinite loop because this code is in the header and it will run again. The header is on every page so redirecting to somewhere else won't help.
The js code to make a facebook login button work, mostly from facebook's step by step guide:
<script>
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
if (response.status === 'connected') {
testAPI();
} else {
document.getElementById('status').innerHTML = 'Please log ' + 'into this app.';
}
}
window.fbAsyncInit = function () {
FB.init({
appId: '(my app id)',
cookie: true,
xfbml: true,
version: 'v2.8'
});
FB.getLoginStatus(function (response) {
statusChangeCallback(response);
});
};
(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/sdk/debug.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function (response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML =
'Thanks for logging in, ' + response.name + '!';
});
get_fb_info();
}
function get_fb_info() {
FB.api('/me', 'GET', {fields: 'first_name,last_name,name,email,id,picture'}, function (response) { //add email,
console.log("FB NAME: " + response.name);
console.log("FB EMAIL: " + response.email);
data_string = 'fb_id=' + response.id + '&f_name=' + response.first_name + '&l_name=' + response.last_name + '&name=' + response.name + '&email=' + response.email + '&picture=' + response.picture;
$.ajax({
type: "POST",
url: "ajax_fb_login.php",
data: data_string,
success: function (data) {
console.log(data);
//location.reload(); only has to happen once
}
})
});
}
</script>
Thanks :)
Based on the official documentation, something like the following should do the trick:
FB.getLoginStatus() allows you to determine if a user is logged in to Facebook and has authenticated your app. There are three possible states for a user: