How to call FB.api outside of window.fbAsyncInit

so i initialized fb api

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 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 undefined.

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

If there is any way to do this?

+4
source share
1 answer

just leave your function queue and then call it immediately after initializing the FB. The following code ensures that your functions will be called in the correct order, and immediately after completing FB initialization

you include the helper script BEFORE THIS EXAMPLE and before starting the FB 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 part of FB:

 window.fbAsyncInit = function() { FB.init(blablabla); processQueue(); } 
+12
source

Source: https://habr.com/ru/post/1437967/


All Articles