未捕获的ReferenceError:使用FB.getLoginStatus时未定义FB

时间:2013-02-28 19:08:14

标签: javascript facebook facebook-login

我正在尝试检查用户是否已使用Facebook登录并在JS控制台中获取该错误。我的代码如下所示:

<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function () {
        FB.init({
            appId: '######', // App ID
            status: true, // check login status
            cookie: true, // enable cookies to allow the server to access the session
            xfbml: true  // parse XFBML
        });
    };

    // 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/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
    }(document));

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

可能是什么问题,是否有任何关于如何修复的消息?

7 个答案:

答案 0 :(得分:52)

在Chrome中,您将收到错误:未捕获的ReferenceError:FB未定义

我喜欢在Facebook的初始化函数 fbAsyncInit()中触发自定义事件。 然后,我不仅限于在fbAsyncInit函数中执行所有与FB相关的脚本编写。我可以把它放在任何地方,只需要监听要触发的自定义事件。

window.fbAsyncInit = function() {
    FB.init({
        appId      : '123456789',
        status     : true,
        cookie     : true,
        xfbml      : true  
    });

    $(document).trigger('fbload');  //  <---- THIS RIGHT HERE TRIGGERS A CUSTOM EVENT CALLED 'fbload'
};

//MEANWHILE IN $(document).ready()
$(document).on(
    'fbload',  //  <---- HERE'S OUR CUSTOM EVENT BEING LISTENED FOR
    function(){
        //some code that requires the FB object
        //such as...
        FB.getLoginStatus(function(res){
            if( res.status == "connected" ){
                FB.api('/me', function(fbUser) {
                    console.log("Open the pod bay doors, " + fbUser.name + ".");
                });
            }
        });

    }
);

答案 1 :(得分:42)

在加载和/或初始化SDK之前,您正在调用FB.getLoginStatus。要等待,那就是fbAsyncInit事件的用途。所以把方法调用放在那里。

答案 2 :(得分:10)

我使用了以下简单的方法,它可以正常工作:

head部分,我加载了SDK:

<script type="text/javascript" src="//connect.facebook.net/en_US/sdk.js"></script>

然后在您的实际内容所在页面的body中,我使用了这个:

<script>

  function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    if (response.status === 'connected') {
      testAPI();

    } else if (response.status === 'not_authorized') {
      FB.login(function(response) {
        statusChangeCallback2(response);
      }, {scope: 'public_profile,email'});

    } else {
      alert("not connected, not logged into facebook, we don't know");
    }
  }

  function statusChangeCallback2(response) {
    console.log('statusChangeCallback2');
    console.log(response);
    if (response.status === 'connected') {
      testAPI();

    } else if (response.status === 'not_authorized') {
      console.log('still not authorized!');

    } else {
      alert("not connected, not logged into facebook, we don't know");
    }
  }

  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  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 + '!';
    });
  }

  $(document).ready(function() {
    FB.init({
      appId      : '1119999988888898981989819891',
      xfbml      : true,
      version    : 'v2.2'
    });
    checkLoginState();
  });
</script>

答案 3 :(得分:2)

只需在标签

中直接使用带有facbook sdk的脚本
    <script type="text/javascript" src="//connect.facebook.net/en_US/all.js#xfbml=1&appId=YOUR_APP_ID" id="facebook-jssdk"></script>

答案 4 :(得分:1)

我们遇到了同样的问题,因为FB sdk没有加载(或加载有延迟),这在某些情况下会导致问题(或破坏javascript),这取决于它。

要解决此问题,我们委托了与facebook相关的所有电话。 我们创建了一个函数:

function callOnFBSDKLoad(callback){
    if (window.isFBInitialized) {
        callback();
    }
    else {
        jQuery(document).bind('fbInitialized', callback);
    }
}

fbInitialized是自定义事件的位置了解有关自定义事件的更多信息here. 加载SDK时window.isFBInitialized是一个变量集。

回调是封闭FB相关事件的方法。 e.g。

var FBLogin = function(){
   FB.login(...);
}

callOnFBSDKLoad(FBLogin)

PS: 请忽略语法和命名约定,我基本上分享了解决此类问题的想法。

答案 5 :(得分:0)

更简单,更可靠的解决方案。 SDK加载时调用函数。我将其命名为triggerLoginCheck()

<script>
  window.fbAsyncInit = function() {
    FB.init({
      //TO DO: Add your unique Facebook app ID (All numbers).
      appId      : '***unique_app_id***',
      cookie     : true,
      xfbml      : true,
      version    : 'v2.8'
    });
    //Call the function here
    triggerLoginCheck();

    FB.AppEvents.logPageView();   
  };

  (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.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
</script>

稍后,在任何地方,放置这个:

function triggerLoginCheck() {       
       FB.getLoginStatus(function(response) {
       statusChangeCallback(response);
       console.log(response);  
       });
}

答案 6 :(得分:0)

对我来说很好。必需包含对象“ Log.info.bind”。

var Log = { info: { bind: function(){ alert('Hi'); testAPI(); } } }