Domanda

Il seguente codice, copiato dalla documentazione Facebook qui , non funziona per 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>

Nella console Javascript ottengo:

Uncaught ReferenceError: FB is not defined

Io non sto avendo problemi con l'SDK in Firefox o Safari, proprio Chrome.

È stato utile?

Soluzione

Ho visto un caso in cui Chrome aveva installato WidgetBlock che stava bloccando lo script di Facebook. Il risultato è stato esattamente questo messaggio di errore. Assicurati di disattivare tutte le estensioni che possono interferire.

Altri suggerimenti

Quindi il problema è in realtà che non si è in attesa di init al completo. Questo farà sì che i risultati casuali. Ecco quello che io uso.

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

Questo farà sì che una volta che tutto viene caricato, la funzione facebookInit è disponibile ed eseguito. In questo modo non c'è bisogno di duplicare il codice di inizializzazione ogni volta che si desidera utilizzare.

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

Questo errore appare anche se si omette il punto e virgola dopo la definizione fbAsyncInit.

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

Senza la virgola, la situazione è la stessa come in questo esempio corta:

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

('bar');

La funzione viene chiamata, perché senza la virgola parte ( 'bar') è visto come una chiamata alla funzione appena definita.

ho incontrato anche questo problema e che cosa risolto non ha nulla a che fare con Facebook, ma la sceneggiatura prima ho incluso che era in cattiva forma

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

L'ho cambiato in

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

E funziona ...

Weew ... Spero che la mia esperienza può aiutare gli altri bloccato in questo che ha fatto quasi di tutto, ma ancora non riesco a farlo funzionare ...

Oh Boy ... ^^

Prova Asynchronous Caricamento: 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>

ho avuto un cody molto disordinato che JavaScript di Facebook caricato tramite la tecnologia AJAX e ho dovuto fare in modo che il file js è stata completamente caricata prima di chiamare FB.init questo sembra funzionare per 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
      });

Questo utilizza codice jQuery per caricare il javascript e fare la funzione di callback OnLoad del javascript. è molto meno disordinata di avere la creazione di un EventListener onLoad per il blocco, che alla fine non ha funzionato molto bene su IE6, 7 e 8

blocchi di AdBlock The Facebook script JS API perché è legato al Facebook Connect che è spesso fastidioso.

Non sono sicuro se hai ancora questo problema, ma ho appena avuto lo stesso problema, si è rivelato ho avuto un'estensione in esecuzione che bloccava Facebook da tutti i siti web che non è Facebook. Disabili che, funzionato!

Usa un setTimeout, perché a volte il FB.init richiede un po 'di tempo per dichiarata

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

Prova a caricare i vostri script nella sezione Head. Inoltre, sarà meglio se si definisce vostri scritti sotto alcuni chiamano come: document.ready, se si è definito questi script nella sezione del corpo

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.

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

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>

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

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.

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

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

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top