40

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.

2

19 Answers 19

52

I saw a case where Chrome had installed WidgetBlock which was blocking the Facebook script. The result was exactly this error message. Make sure you disable any extensions that may interfere.

9
  • Thanks a million. My chrome synced the widgetblock extension from my home computer to the workplace. Fun bug.
    – Kit Sunde
    Commented Jul 1, 2011 at 5:09
  • 6
    FYI - this chrome extension also caused the problem - "Facebook Disconnect" - chrome.google.com/webstore/detail/…
    – Jody
    Commented Feb 29, 2012 at 16:05
  • 7
    Ah, I was using "Facebook Disconnect" Commented Mar 31, 2012 at 2:33
  • 3
    Disconnect was the problem for me. Commented Apr 9, 2013 at 13:39
  • 3
    Disconnect for me also was the problem!
    – Clint C.
    Commented Jun 27, 2014 at 15:27
49

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
}
2
  • 2
    Thank you for this. Just saved me from having to use sync instead of async. +1 to you Commented Feb 22, 2012 at 15:53
  • I actually had to remove the call to FB.init() to make the above snippet work.
    – ripper234
    Commented Aug 28, 2012 at 14:01
24

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.

3
  • 1
    this is really weird, but it actually happened to me. What's wrong with omitting the semi-colon? I mean, you shouldn't for a clean code, but JS is not so choosy, right? Commented Apr 5, 2013 at 12:35
  • 2
    Awsome! That was the problem! But I also wonder why it was so important.
    – Paul Lysak
    Commented Aug 9, 2013 at 12:02
  • 1
    Awesome.. this just spared me 500 years of pulling my hair out :)
    – Alex
    Commented Feb 16, 2015 at 10:47
5

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

1
  • Same mistake here... Had a big headache before i got to your post. No error was shown and the FB JS SDK wasn't loading at all if the previous script (like jquery) was in that format.
    – Aleja_Vigo
    Commented Mar 7, 2012 at 12:32
4

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>
3
  • 1
    Still gives me the same issue. Works in Firefox / Safari, doesn't work in Chrome. Commented Dec 29, 2010 at 19:05
  • 1
    ok, try a event: window.onload = function(){ /* Init code*/ } Commented Dec 29, 2010 at 19:07
  • 1
    Same thing! I actually had it like that originally. Still getting "FB not defined." Gaaah! Thanks for the suggestions though! Commented Dec 29, 2010 at 19:39
4

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

3

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

2

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!

2

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);
1

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

1

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.

1

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);
    });
1

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.

1

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>
0

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

0

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.

0

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 ;)

-1

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

-2

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

1
  • you are still using the FB object, and you're not sure whether it exists or not Commented Feb 27, 2014 at 11:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.