FB.api does not work when called right after FB.init

ぐ巨炮叔叔 提交于 2019-12-22 18:42:41

问题


FB.api does not work when called right after FB.init. Here is the code snippet I use:

window.fbAsyncInit = function() {
  FB.init({
    appId : window.APP_ID,
    status : true,
    cookie : true,
    oauth : true,
    channelUrl : window.MASTER_URL + "channel",
    frictionlessRequests : true
  });

  window.COMPANY.init();
};

(function() {
  var e = document.createElement('script');
  e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
  e.async = true;
  document.getElementById('fb-root').appendChild(e);
}());

And here is my COMPANY.init() and COMPANY.fetchAllFriends():

friends: new Array(),

init : function() {
  // TODO

  COMPANY.fetchAllFriends();

  FB.Canvas.setSize($(document).height());
  FB.Canvas.setAutoGrow();
},    

fetchAllFriends : function() {
  FB.api('/me/friends', function(response) {
    if (!response || response.error) {
      return;
    }

    COMPANY.friends = new Array();
    $.each(response.data, function(index, value) {
      COMPANY.friends.push(value.id);
    });
  });
},

where at fetchAllFriends response contains error which says "An active access token must be used to query information about the current user.". I made sure (via the browsers debugger) that FB.init is called before that call of FB.api.

Any help will be appreciated!


回答1:


Ok, I fixed my problem. I changed:

window.fbAsyncInit = function() {
  FB.init({
    appId : window.APP_ID,
    status : true,
    cookie : true,
    oauth : true,
    channelUrl : window.MASTER_URL + "channel",
    frictionlessRequests : true
  });

  window.COMPANY.init();
};

to:

window.fbAsyncInit = function() {
  FB.init({
    appId : window.APP_ID,
    status : true,
    cookie : true,
    oauth : true,
    channelUrl : window.MASTER_URL + "channel",
    frictionlessRequests : true
  });

  FB.Event.subscribe('auth.login', window.COMPANY.init);
};

in case anyone else want to know. What I found is that the FB JS SDK has not formed the user session by the time when FB.init returns, so what you need to do is to subscribe to the 'auth.login' event with your init function. More info here




回答2:


You don't appear to be checking the status of the user. All you are doing is initializing Facebook, you don't even know if the user is logged into Facebook or has a Facebook account. You need to call FB.getLoginStatus and check if they are "connected". If they aren't connected, there is no possible way to get an access token. If they are connected, then you get an access token.



来源:https://stackoverflow.com/questions/8494280/fb-api-does-not-work-when-called-right-after-fb-init

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!