javascript - Facebook Javascript API 不断重新连接

标签 javascript facebook api facebook-graph-api facebook-javascript-sdk

我正在构建一个网站,当用户连接到 Facebook 时,该网站会将个人资料图片附加到 div 等内容中。当我让网站打开一段时间然后回来时,我看到同一张个人资料图片已被附加多次,因此很明显 Facebook 连接会经常关闭并重新打开。

有什么办法可以阻止这种情况吗?

谢谢

<script>
  window.fbAsyncInit = function() {
  FB.init({
    appId      : '219892158204692',
    status     : true, // check login status
    cookie     : true, // enable cookies to allow the server to access the session
    xfbml      : true  // parse XFBML
  });

  // Here we subscribe to the auth.authResponseChange JavaScript event. This event is fired
  // for any authentication related change, such as login, logout or session refresh. This means that
  // whenever someone who was previously logged out tries to log in again, the correct case below
  // will be handled.
  FB.Event.subscribe('auth.authResponseChange', function(response) {
    // Here we specify what we do with the response anytime this event occurs.
    if (response.status === 'connected') {
        fbconnect = true;
        $('#fbloginbutton').hide();
        $('#friendcontainer').append('<span id="loader"><center>Loading...</center></span>');
      // The response object is returned with a status field that lets the app know the current
      // login status of the person. In this case, we're handling the situation where they
      // have logged in to the app.
        FB.api(
            "/me",
            function (response) {
                if (response && !response.error) {
                fbid = response['id'];
                user['id'] = response['id'];
                getuserhighscore(user['id']);
                userpercentile(parseInt(user['highscore']));
                $('#statscontainer').append('<span class="label">Highest Score</span>: '+user['highscore']+'<br>');
                $('#statscontainer').append('<span class="label">Percentile (global)</span>: '+user['percentile']+'<br>');
                drawuserchart(user['id']);

                }
            }
        );



        FB.api(
            "/fql?q=select%20uid%2C%20first_name%2C%20is_app_user%20from%20user%20where%20uid%20in%20(select%20uid2%20from%20friend%20where%20uid1%3Dme())%20and%20is_app_user%3D1",
            function (response) {
                console.log('friends installed:');
                console.log(response);
                console.log(response['data'][0].id);
                var responseArray = []; 
                responseArray.push(response);
                console.log(responseArray); 
                user['friends'] = response['data'].length;
                if (response && !response.error) {
                    for (var i=0;i<response['data'].length;i++){
                        friend = response['data'][i];
                        console.log('friend coming up');
                        console.log(friend);
                        friends.push(friend.uid);
                        $('#friendcontainer').append('<div class="friendbox" id="'+friend.uid+'"></div>');
                           $('#'+friend.uid+'').append('<img class="friendpic" src="https://graph.facebook.com/'+friend.uid+'/picture?height=60&width=60&type=square">');
                           $('#'+friend.uid+'').append('<div class="friendname">'+friend.first_name+'</div>');
                        gethighscore(friend.uid);
                        $('#'+friend.uid+'').append(' - '+friendscores[i]+'');
                        console.log(friendscores);
                    }
                    $('#loader').remove();

                    user['friendrank'] = 1;



                    for (var i=0;i<friendscores.length;i++){
                        if(friendscores[i] > user['highscore']){
                            user['friendrank']++;
                        }
                    }

                    $('#statscontainer').append('<span class="label">Rank (among friends)</span>: '+user['friendrank']+'<br>');

                } else { 
                    console.log(response.error) 
                }
            }
        );
        console.log(friends);
        console.log(user)
        FB.api(
            "/me/picture",
            {
                "redirect": false,
                "height": "100",
                "type": "normal",
                "width": "100"
            },
            function (response) {
              if (response && !response.error) {
                user['picture'] = response['data']['url'];
                console.log(user['picture']);
                $('#thumbnail').append('<img id="thumbnailpic" src="'+user['picture']+'">');
              }
            }
        );
      testAPI();
    } else if (response.status === 'not_authorized') {
      // In this case, the person is logged into Facebook, but not into the app, so we call
      // FB.login() to prompt them to do so.
      // In real-life usage, you wouldn't want to immediately prompt someone to login
      // like this, for two reasons:
      // (1) JavaScript created popup windows are blocked by most browsers unless they
      // result from direct interaction from people using the app (such as a mouse click)
      // (2) it is a bad experience to be continually prompted to login upon page load.
      FB.login();
    } else {
      // In this case, the person is not logged into Facebook, so we call the login()
      // function to prompt them to do so. Note that at this stage there is no indication
      // of whether they are logged into the app. If they aren't then they'll see the Login
      // dialog right after they log in to Facebook.
      // The same caveats as above apply to the FB.login() call here.
      FB.login();
    }
  });
  };

  // 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));

  // Here we run a very simple test of the Graph API after login is successful.
  // This testAPI() function is only called in those cases.
  function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Good to see you, ' + response.name + '.');
      $('#sidebar').slideDown("slow");
    });
  }
</script>

最佳答案

每当身份验证发生更改时,就会触发 auth.authResponseChange 上的

FB.Event.subscribe。用户 session 会维持几分钟,因此一段时间后会触发事件并再次附加照片。

您不应该在此事件 block 中编写整个代码。

因此,如果您想在同一页面中完成所有这些操作,您可以做的是维护一个 bool,例如 bool isLoaded=false;,现在当您的调用完成时:isLoaded=true;表示数据已加载。

只要它为 false,就进行 API 调用,就像这样 -

if (response.status === 'connected') {
   if(isLoaded){
      fbconnect = true;
      ....
      ....
   }
   else
      // dont do anything
}

希望有帮助!

关于javascript - Facebook Javascript API 不断重新连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23034427/

相关文章:

javascript - 如何将对象插入同一个数组?

javascript - 如何在 HTML 中显示消息并关闭设置窗口?

函数中的 JavaScript 函数

facebook - 简单的 Facebook 应用程序,没有权限,但添加滥用保护/用户跟踪?

javascript - 从 phonegap facebook 登录获取用户 ID

Facebook Open Graph API 示例 - 如何获取访问 token ?

java - Maven:maven 构建中的类下缺少文件

javascript - 当获得以下代码的输出时,为什么 i 的值显示未定义

c++ - 如何修复无效的 API key 、IP 或操作错误权限?

php - Facebook API : show dialog window for the user select page (manage_pages extendend perm)