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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15143671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:40:38  来源:igfitidea点击:

Uncaught ReferenceError: FB is not defined when using FB.getLoginStatus

javascriptfacebookfacebook-login

提问by Xeen

I'm trying to check if a user has logged in using facebook and get that error in JS console. My code looks like this:

我正在尝试检查用户是否已使用 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>

What could be the problem and are there any sugestions on how to fix it?

可能是什么问题,是否有任何关于如何解决它的建议?

回答by jairbow

In Chrome, you'd be getting the error: Uncaught ReferenceError: FB is not defined.

在 Chrome 中,您会收到错误:Uncaught ReferenceError: FB is not defined

I like to trigger a custom event in Facebook's initialization function, fbAsyncInit(). Then I'm not limited to doing all my FB related scripting inside of the fbAsyncInit function. I can put it anywhere, by just listening for that custom event to be fired.

我喜欢在 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 + ".");
                });
            }
        });

    }
);

回答by CBroe

You are calling FB.getLoginStatus before the SDK is loaded and/or initialized. To wait for that, that's what the fbAsyncInit event is for. So put the method call in there.

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

回答by basZero

I used the following simple approach and it works correctly:

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

In the headsection I load the SDK:

head我加载 SDK的部分中:

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

Then in the bodyof your page where your actual content is, I used this:

然后在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>

回答by VnDevil

Simply using script with facbook sdk directly in tag

只需在标签中直接使用带有 facbook sdk 的脚本

    <script type="text/javascript" src="//connect.facebook.net/en_US/all.js#xfbml=1&appId=YOUR_APP_ID" id="facebook-jssdk"></script>

回答by Mohit Kanwar

We were facing the same issue, and since FB sdk was not loading (or loading with delays) this was causing problems (or breaking javascript)in some cases which were dependent upon that.

我们面临着同样的问题,并且由于 FB sdk 没有加载(或加载延迟),这在某些依赖于此的情况下会导致问题(或破坏 javascript)。

To resolve this issue, we delegated all the calls related to facebook. We created a function like :

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

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

Where fbInitializedis a custom event learn more about custom events here.And window.isFBInitializedis a variable set when SDK is loaded.

fbInitialized自定义事件在哪里可以在此处了解有关自定义事件的更多信息并且window.isFBInitialized是加载 SDK 时设置的变量。

callback is the method enclosing FB related events. e.g.

callback 是封闭 FB 相关事件的方法。例如

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

callOnFBSDKLoad(FBLogin)

PS: Please ignore syntax and naming conventions, I am basically sharing the idea to resolve such issues.

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

回答by George Chalhoub

A simpler and solid solution. Call a function when the SDK loads. I will name it triggerLoginCheck().

一个更简单和可靠的解决方案。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>

Later, anywhere, place this:

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

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

回答by Claudio Garaycochea

It's work fine for me. Is necessary include the Object "Log.info.bind".

这对我来说很好用。必须包括对象“Log.info.bind”。

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