我尝试使用facebook javascript SDK让我的应用连接到用户的Facebook帐户。
在运行代码连接之前,是否有一种简单的方法可以检查我的应用是否已连接到Facebook?它必须重新加载页面,以便用户可以实际看到他们通过Facebook登录,但如果我做location.reload();最后它将进入一个无限循环,因为此代码在标题中,它将再次运行。标题在每个页面上,因此重定向到其他地方不会有帮助。
使Facebook登录按钮工作的js代码,主要来自Facebook的分步指南:
<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>
谢谢:)
答案 0 :(得分:2)
根据官方文档,以下内容应该可以解决问题:
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.
}
});
FB.getLoginStatus()允许您确定用户是否已登录Facebook并已对您的应用进行身份验证。用户有三种可能的状态: