[javascript] Facebook Javascript SDK Problem: "FB is not defined"

The following code, copied from the Facebook documentation here, is not working for me in Chrome.

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
  FB.init({
  appId  : 'YOUR APP ID',
  status : true, // check login status
  cookie : true, // enable cookies to allow the server to access the session
  xfbml  : true  // parse XFBML
});
</script>

In the Javascript console I get:

Uncaught ReferenceError: FB is not defined

I'm not having any problems with the SDK in Firefox or Safari, just Chrome.

The answer is


Use a setTimeout, because sometimes the FB.init takes some time to get declared

function testAPI() {
     console.log('Welcome!  Fetching your information.... ');
     FB.api('/me', function(response) {
         console.log('Good to see you, ' + response.name + '.');
     });
}
function login() {
    FB.login(function(response) {
        if (response.authResponse) {
            testAPI();
        } else {
            // cancelled
        }
    });
}
setTimeout(function() {
    login();
},2000);

If you're using JQuery, try putting FB withing Jquery call

e.g.

$(document).ready(function(){
    FB.Event.subscribe('auth.login', function(){
        alert('logged in!');
    });
});

that worked for me


I had the same problem and the only solution I found was putting everything that used the FB statement inside the init script, I also used async loading, so the callback function is after everything that needs FB. I have a common page dinamycally loaded with php so many parts need different facebook functions controlled by php if statements which is making everything a bit messy, but is working!. if I try taking any FB declaration out of the loading script, then firefox shows the "FB is not defined" message. Hope it helps in anything.


Try Asynchronous Loading: http://developers.facebook.com/docs/reference/javascript/fb.init/

<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
    FB.init({
      appId  : 'YOUR APP ID',
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml  : true  // parse XFBML
    });
  };

  (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);
  }());
</script>

Facebook prefers that you load their SDK asynchronously so that it doesn't block any other scripts that you need for your page but due to the iframe there's a chance that the console tries to call a method on the FB object before the FB object is completely created even though FB is only called in the fbAsyncInit function.
Try loading the javascript synchronously and you shouldn't get the error anymore. To do this you can copy and paste the code that Facebook provides and place it in an external .js file and then include that .js file in a <script> tag in the <head> of your page. If you must load their SDK asynchronously then check for FB to be created first before calling the init function.


So the issue is actually that you are not waiting for the init to complete. This will cause random results. Here is what I use.

window.fbAsyncInit = function () {
    FB.init({ appId: 'your-app-id', cookie: true, xfbml: true, oauth: true });

    // *** here is my code ***
    if (typeof facebookInit == 'function') {
        facebookInit();
    }
};

(function(d){
    var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
    js = d.createElement('script'); js.id = id; js.async = true;
    js.src = "//connect.facebook.net/en_US/all.js";
    d.getElementsByTagName('head')[0].appendChild(js);
}(document));

This will ensure that once everything is loaded, the function facebookInit is available and executed. That way you don't have to duplicate the init code every time you want to use it.

function facebookInit() {
   // do what you would like here
}

I had the same problem and I've found the cause.

I have avast! antivirus installed in my computer, and it asked me to install the update for chrome plugin. The new avast! plugin for chrome has the functionality to block ads and tracking, and, by default, it blocks the facebook access. I have solved my problem simply allowing facebook in the avast! chrome plugin for the website I needed.

Since this question is very old, I think that some people might have the same cause as me, the new avast! chrome plugin.


I had a similar issue and it turned out to be Adblocker Pro. Be sure to check that this or other blocking extensions have been disabled. I lost around 1hr 30 mins due to this. Feel like such a noob ;)


To test Mattys suggestions about FB not finishing, I put an alert in the script. This cause a delay that I could control. Sure enough... it was a timing issue.

    $("document").ready(function () {
        // Wait...
        alert('Click ok to init');
        try {
            FB.init({
                appId: '###', // App ID
                status: true, // check login status
                cookie: true, // enable cookies to allow the server to access the session
                xfbml: true  // parse XFBML
            });
        }
        catch (err) {
            txt = "There was an error on this page.\n\n";
            txt += "Error description: " + err.message + "\n\n";
            txt += "Click OK to continue.\n\n";
            alert(txt);
        }
        FB.Event.subscribe('auth.statusChange', OnLogin);
    });

I had the same problem. The solutions was to use core.js instead of debug.core.js


I encountered this problem too and what solved it has nothing to do with Facebook but the prior script I included that was in bad form

<script type="text/javascript" src="js/my_script.js" />

I changed it to

<script type="text/javascript" src="js/my_script.js"></script>

And it works...

Weew... hopefully my experience can help others stuck in this that has done almost about everything but still can't get it to work...

Oh Boy... ^^


AdBlock blocks the facebook JS api scripts because it's related to facebook connect which is often annoying.


I had a very messy cody that loaded facebook's javascript via AJAX and i had to make sure that the js file has been completely loaded before calling FB.init this seem to work for me

    $jQuery.load( document.location.protocol + '//connect.facebook.net/en_US/all.js',
      function (obj) {
        FB.init({
           appId  : 'YOUR APP ID',
           status : true, // check login status
           cookie : true, // enable cookies to allow the server to access the session
           xfbml  : true  // parse XFBML
        });
        //ANy other FB.related javascript here
      });

This code uses jquery to load the javascript and do the function callback onLoad of the javascript. it's a lot less messier than having creating an onLoad eventlistener for the block which in the end didn't work very well on IE6, 7 and 8


Have you set the appId property to your current application ID?


This error will also appear if you omit the semicolon after the fbAsyncInit definition.

window.fbAsyncInit = function() {
    FB.init({
        appId: 'YOUR APP ID',
        status: true,
        cookie: true,
        xfbml: true
    });
    //do stuff
}; //<-- semicolon required!

Without the semicolon, the situation is the same as in this shorter example:

var x = function () {
    console.log('This is never called. Or is it?');
}

('bar');

The function gets called, because without the semicolon the ('bar') part is seen as a call to the function just defined.


Not sure if you're still having this problem, but I just had the same problem, turned out I had an extension running that was blocking Facebook from all websites that is not Facebook. Disabled it, worked!


There is solution for you :)

You must run your script after window loaded

if you use jQuery, you can use simple way:

<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function() {
        FB.init({
            appId      : 'your-app-id',
            xfbml      : true,
            status     : true,
            version    : 'v2.5'
        });
    };

    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>

<script>
$(window).load(function() {
    var comment_callback = function(response) {
        console.log("comment_callback");
        console.log(response);
    }
    FB.Event.subscribe('comment.create', comment_callback);
    FB.Event.subscribe('comment.remove', comment_callback);
});
</script>

Try to load your scripts in Head section. Moreover, it will be better if you define your scripts under some call like: document.ready, if you defined these scripts in body section


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to google-chrome

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 SameSite warning Chrome 77 What's the net::ERR_HTTP2_PROTOCOL_ERROR about? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Jupyter Notebook not saving: '_xsrf' argument missing from post How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to make audio autoplay on chrome How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

Examples related to facebook

I am receiving warning in Facebook Application using PHP SDK React-Native: Application has not been registered error Can't Load URL: The domain of this URL isn't included in the app's domains Facebook OAuth "The domain of this URL isn't included in the app's domain" Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings." Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView` Open Facebook Page in Facebook App (if installed) on Android App not setup: This app is still in development mode IOS - How to segue programmatically using swift Get ALL User Friends Using Facebook Graph API - Android

Examples related to facebook-javascript-sdk

Chrome violation : [Violation] Handler took 83ms of runtime "Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query How to add facebook share button on my website? Given URL is not permitted by the application configuration How to get access token from FB.login method in javascript SDK Facebook API error 191 Facebook Javascript SDK Problem: "FB is not defined"