Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call FB.api outside window.fbAsyncInit

so i have fb api initialized

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

and i have a separate js file with a function:

function example(){
  FB.api(
    '/me/[namespace]:visit',
    'post',
    { channel: link},
    function(response) {
       if (!response || response.error) {
          console.log(response.error);
       } else {
          console.log('Follow was success! Action ID: ' + response);
       }
    });
 }

when i call this i get FB is undefined.

When i put the function inside window.fbAsyncInit it works ok , but i need to call the FB outside window.fbAsyncInit.

If there any possible way to do that?

like image 650
linderman Avatar asked Dec 16 '22 18:12

linderman


1 Answers

just queue your function, and then call it right after FB initialized. Following code guarantees that your functions will be called in right order, and right after FB finish initialization

helper script you include BEFORE your example and before FB init script:

var FB; // to avoid error "undeclared variable", until FB got initialized
var myQueue = new Array();
function queueAdd(f){
  if (FB == undefined)
    myQueue.push(f);
  else
    f();
}

function processQueue(){
  var f;
  while(f = myQueue.shift())
    f();
}

your function example:

function example(){
  FB.api(
    '/me/[namespace]:visit',
    'post',
    { channel: link},
    function(response) {
       if (!response || response.error) {
          console.log(response.error);
       } else {
          console.log('Follow was success! Action ID: ' + response);
       }
    });
 }

queueAdd(example); // will run immediately if FB initialized. Otherwise, wait for FB first

and FB part:

window.fbAsyncInit = function() {
  FB.init(blablabla);
  processQueue();
}
like image 50
Viktor Avatar answered Jan 11 '23 23:01

Viktor