FB init function gives wrong version error

后端 未结 20 1388
故里飘歌
故里飘歌 2020-12-08 18:18

I\'m using the Facebook JS sdk, and I have created a new App today. Everything is configured properly. Using init function like:

window.fbAsyncInit = functio         


        
20条回答
  •  情书的邮戳
    2020-12-08 19:08

    For single page applications (React in my case)

    In single page applications you have less control about the order in which the code will run. Sometimes the script will have loaded by the time you call your code, sometimes not.

    To make it work regardless of whether the facebook script has already loaded or not, I do a check whether the FB global variable is already defined at the moment of running the code. If so, I just do a normal initialize, otherwise I provide the callback.

    This is my code:

    export function initializeFacebookSdk() {
    
      /* Asynchronous flow: if the global 'FB' variable is still undefined,
         then the facebook script hasn't loaded yet, in that case, provide
         a global callback that will be called by the facebook code. If the 
         variable is already present, just call the code right away and forget
         about the callback. */
      if(window.FB === undefined) {
        console.log('FB undefined -> provide callback');
        window.fbAsyncInit = function() {
          initialize();
        };
      }
      else {
        console.log('FB defined -> call init right away');
        initialize();
      }
    
      function initialize() {
        window.FB.init({
          appId      : '492331311256888',
          cookie     : true,
          xfbml      : true,
          version    : 'v3.2'
        });    
      }
    }
    

    In my html file I just provide the script given by facebook, and in my code I can call initializeFacebookSdk() wherever and whenever I want:

    
    
      
        My application
      
          
        
    
        
    
        

提交回复
热议问题