问题描述
我有一个页面,其中有一个按钮可以触发 FB.login 功能,我正在尝试在响应状态为“已连接”后对 accesstoken 进行 console.log,我还想重定向到一个页面作为测试使用 window.location.href
但都不起作用。
当我登录时,弹出窗口出现,成功登录后,弹出窗口关闭,我仍然在带有登录按钮的初始页面上,但我放置在 if 语句中的任何代码似乎都没有发生任何事情。 facebook 文档非常模糊,没有很好的例子说明登录后我需要做什么。
function fb_login() {
FB.login(function(response){
if(response.status === 'connected'){
var accesstoken = response.authResponse.accesstoken;
console.log(accesstoken)
window.location.href = "https://google.com";
}
});
}
这是 html 按钮:
<div data-scope="public_profile,email,pages_read_engagement,pages_show_list" class="fb-login-button" data-width="" data-size="large" data-button-type="continue_with" data-layout="default" data-auto-logout-link="true" data-use-continue-as="true"></div>
解决方法
好吧,我误解了流程。修复是删除 fb_login 函数,因为该按钮已经触发弹出窗口登录。然后我将 data-onlogin="loginStatus()"
添加到 html 按钮以触发 FB.getLoginStatus
,然后我现在可以访问页面上的令牌并在需要时发送到服务器。
<div data-onlogin="loginStatus()" data-scope="public_profile,email,pages_read_engagement,pages_show_list" class="fb-login-button" data-width="" data-size="large" data-button-type="continue_with" data-layout="default" data-auto-logout-link="true" data-use-continue-as="true"></div>
function loginStatus(){
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;
console.log(accessToken)
} else if (response.status === 'not_authorized') {
// The user hasn't authorized your application. They
// must click the Login button,or you must call FB.login
// in response to a user gesture,to launch a login dialog.
} else {
// The user isn't logged in to Facebook. You can launch a
// login dialog with a user gesture,but the user may have
// to log in to Facebook before authorizing your application.
}
});
}