How to detect when facebook's FB.init is complete

后端 未结 12 2290
我寻月下人不归
我寻月下人不归 2020-11-28 01:28

The old JS SDK had a function called FB.ensureInit. The new SDK does not seem to have such function... how can I ensure that I do not make api calls until it is fully initia

12条回答
  •  情歌与酒
    2020-11-28 02:15

    Update on Jan 04, 2012

    It seems like you can't just call FB-dependent methods (for example FB.getAuthResponse()) right after FB.init() like before, as FB.init() seems to be asynchronous now. Wrapping your code into FB.getLoginStatus() response seems to do the trick of detecting when API is fully ready:

    window.fbAsyncInit = function() {
        FB.init({
            //...
        });
    
        FB.getLoginStatus(function(response){
            runFbInitCriticalCode(); 
        });
    
    };  
    

    or if using fbEnsureInit() implementation from below:

    window.fbAsyncInit = function() {
        FB.init({
            //...
        });
    
        FB.getLoginStatus(function(response){
            fbApiInit = true;
        });
    
    };  
    

    Original Post:

    If you want to just run some script when FB is initialized you can put some callback function inside fbAsyncInit:

      window.fbAsyncInit = function() {
        FB.init({
          appId  : '',
          status : true, // check login status
          cookie : true, // enable cookies to allow the server to access the session
          xfbml  : true  // parse XFBML
        });
        FB.Canvas.setAutoResize();
    
        runFbInitCriticalCode(); //function that contains FB init critical code
      };
    

    If you want exact replacement of FB.ensureInit then you would have to write something on your own as there is no official replacement (big mistake imo). Here is what I use:

      window.fbAsyncInit = function() {
        FB.init({
          appId  : '',
          status : true, // check login status
          cookie : true, // enable cookies to allow the server to access the session
          xfbml  : true  // parse XFBML
        });
        FB.Canvas.setAutoResize();
    
        fbApiInit = true; //init flag
      };
    
      function fbEnsureInit(callback) {
            if(!window.fbApiInit) {
                setTimeout(function() {fbEnsureInit(callback);}, 50);
            } else {
                if(callback) {
                    callback();
                }
            }
        }
    

    Usage:

    fbEnsureInit(function() {
        console.log("this will be run once FB is initialized");
    });
    

提交回复
热议问题