在页面加载时检查Facebook登录状态

时间:2013-03-30 18:13:49

标签: javascript facebook

根据Facebook Javascript SDK documentation

  

可以通过设置status:true来检查用户的状态   当你打电话给FB.init。

     

要接收此通话的回复,您必须订阅   auth.statusChange事件。

我相信我这样做是正确的,但我的示例中的'状态更改'日志永远不会触发:

window.fbAsyncInit = function() {
    FB.init({
        appId      : 'xxxxxxxxxxxx', // App ID
        channelUrl : '../channel.html', // Channel File
        status     : true, // check login status
        cookie     : true, // enable cookies to allow the server to access the session
        xfbml      : true  // parse XFBML
    });

    FB.Event.subscribe('auth.statusChange', function(response) {
        console.log("status change!");
    });
    ...
});

此文档是否不正确?或者我做错了什么?

2 个答案:

答案 0 :(得分:0)

我认为最后而不是});是};

也可能是你没有开始。这对我有用:

$(document).ready(function() {

  var app_id = 'xxxxxxxxxxxxxx';

  var start = function (){


    window.fbAsyncInit = function() {

     FB.init({

        appId     : app_id,
        status    : true,
        cookie    : true,
        xfbml     : true,
        version   : 'v2.7'

     });

     FB.Event.subscribe('auth.statusChange', function(response) {
        var status = response.status;
        console.log(response.status);

        if (status === "connected") {
         //
        }

     });
   };

  }

  start();

 });

答案 1 :(得分:0)

您可以尝试这种方式。

<script type="application/javascript">

    function statusChangeCallback(response) {  // Called with the results from FB.getLoginStatus().
        console.log('statusChangeCallback');
        console.log(response);                   // The current login status of the person.
        if (response.status === 'connected') {   // Logged into your webpage and Facebook.
            console.log("User connected, name: " + response.name);
        } else {                                 // Not logged into your webpage or we are unable to tell.
            console.log("user not conneted");
        }
    }

    window.fbAsyncInit = function () {
        FB.init({
            appId: '{your-app-id}',
            cookie: true,
            xfbml: true,
            version: '{api-version}'
        });

        FB.getLoginStatus(function (response) {   // Called after the JS SDK has been initialized.
            statusChangeCallback(response);        // Returns the login status.
        });
    };

    (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 = "https://connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>