我試圖使用Facebook的JavaScript SDK讓我的應用程序連接到用戶的Facebook帳戶。Facebook登錄按鈕 - 如何在嘗試登錄前檢查我們是否已登錄?
是否有一個簡單的方法來檢查我的應用程序是否已經連接到Facebook之前運行代碼連接它?它必須重新加載頁面,以便用戶可以真正看到他們通過Facebook登錄,但是如果我做了location.reload();在最後它會進入一個無限循環,因爲這個代碼在頭文件中,並且它會再次運行。標題在每個頁面上,因此重定向到別的地方都無濟於事。
的JS做一個Facebook登錄按鈕的工作,大部分來自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>
謝謝:)
在FB.init參數中添加'status:true',以便SDK實際檢查當前的登錄狀態。 – CBroe