环顾谷歌和 StackOverflow,每个人实际上都有相同的建议:
FB.login(function(response) {
if (response.authResponse) {
var accessToken = response.authResponse.accessToken;
}
});
我在页面上有一个“分享”按钮,当点击时我只想在用户的个人资料上发布一个帖子,并使用https://graph.facebook.com/me/feed调用来做到这一点。为了能够做到这一点,我需要来自 facebook 的 access_token,所以我所做的是:
(在调用 FB.init() 以及添加 all.js 之后)
FB.login(function (response) {
console.log('response.authResponse: ' + response.authResponse);
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = ' + access_token);
FB.api('/me', function (response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, { scope: 'user_about_me' });
我期望发生的是它会为用户打开一个登录对话框到 facebook,一旦他们登录,对话框就会关闭,它会返回到我的页面并且我得到访问令牌。
但是发生的情况是,它会使用登录对话框向 facebook 生成一个新的浏览器窗口,一旦用户登录,页面就会进入用户的新闻提要页面,并且我上面的回调永远不会被调用。所以基本上控制已经消失并转移到新的浏览器窗口,作为用户的正常 facebook 浏览。但是,当我关闭该新窗口时,它会在我的日志记录中执行“用户取消登录”。
我在这里想念什么?所有资源都只是建议调用 FB.login ,这就是我已经在做的事情,但我似乎无法为用户获取访问令牌。
提前致谢!
编辑:完整代码和更多评论
<script type="text/javascript" language="javascript">
window.fbAsyncInit = function ()
{
FB.init(
{
appId: '<%= this.ApplicationId %>', // App ID
channelURL: '<%= this.ChannelFileUrl %>', // Channel File
status: true, // check login status
cookie: true, // enable cookies to allow the server to access the session
oauth: true, // enable OAuth 2.0
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/<%= this.LocaleCode %>/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
} (document));
</script>
然后在一些js文件中调用这个函数(参数还没有被使用,因为还没有真正发帖)
function postToFacebook(name, caption, description, link, picture, id) {
var accessToken = "";
console.log('fb event subscribe');
FB.Event.subscribe('auth.login', function () {
console.log('facebook event auth.login');
});
console.log('fb login');
FB.login(function (response) {
console.log('response.authResponse: ' + response.authResponse);
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = ' + access_token);
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {});
}
发生的顺序是:
- 打印 'fb 事件订阅'
- 打印'fb登录'
- 代码命中 FB.login -> 向 facebook 打开一个新的浏览器窗口,用户登录后焦点停留在该新窗口中,它永远不会进入 FB.login 中的回调函数
- 如果我关闭上面第 3 步中生成的窗口,则会调用回调函数并“用户取消登录或未完全授权”。被打印('response.authResponse:' 给出空值)
第 1 步和第 2 步是预期的,第 3 步是问题所在,打开的窗口也有 url https://www.facebook.com/home.php?_rdr