用户使用Facebook登录时如何触发事件

时间:2012-05-13 03:16:01

标签: facebook facebook-apps

我已经设置了

<div id="fb-root"></div><div class="fb-login-button" data-show-faces="true" data-width="400" data-max-rows="1" scope="email, publish_stream"></div><script type="text/javascript">
window.fbAsyncInit = function () {
    FB.init({
        appId: 'xxx', // App ID
        status: true, // check login status
        cookie: true, // enable cookies to allow the server to access the session
        xfbml: true,  // parse XFBML,
        oauth : true
    });

    FB.Event.subscribe('auth.authResponseChange', 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;

            // TODO: Handle the access token

            $.post('/facebook/login', { accessToken: accessToken }, function (response) { if(response) {alert('Logged in')} });

        } 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.
        }
    });


};

// Load the SDK Asynchronously
(function (d) {
    var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
    if (d.getElementById(id)) { return; }
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    ref.parentNode.insertBefore(js, ref);
} (document));

问题是当用户点击“登录”按钮并接受我的应用程序时,登录对话框已关闭且没有事件被触发,因此我的帖子$ .post('/ facebook / login')也从未被解雇,除非我按F5。

如何在登录对话框关闭后立即触发事件?

2 个答案:

答案 0 :(得分:0)

只是分享。 在阅读Facebook文档以获取答案时,请运行可能的解决方案。

http://facebook.stackoverflow.com/questions/3548493/how-to-detect-when-facebooks-fb-init-is-complete

您可以在fbEnsureInit()中运行$ .post('/ facebook / login'); &lt; - 指的是serg的答案。

使用间隔回调来检查登录状态可能是一种方法。

答案 1 :(得分:-1)

您可以使用以下代码重新加载页面:window.location.reload();,这样您就不需要按F5,

FB.login示例:

FB.login(function(response) {
    if (response.authResponse) {
        console.log('Application authorized.');
        window.location.reload();
    } else {
        console.log('You cancelled login or you did not fully authorize the app.');
    }
}, { scope: 'email' });

或者您可以使用订阅活动:

FB.Event.subscribe('auth.authResponseChange', function(response) {
    console.log('The status of the session changed to: '+response.status);
    window.location.reload();
});