FB init函数给出错误的版本错误。

时间:2022-06-09 18:44:14

I'm using the Facebook JS sdk, and I have created a new App today. Everything is configured properly. Using init function like:

我使用的是Facebook JS sdk,今天我创建了一个新的应用程序。一切都正确配置。使用init函数:

window.fbAsyncInit = function() {
    FB.init({
      appId      : 'xxxx', // App ID
      status     : false, 
      version:  'v2.0',
      cookie     : true, 
      xfbml      : false  // parse XFBML
    });
};

    (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/pl_PL/sdk.js";
         fjs.parentNode.insertBefore(js, fjs);
       }(document, 'script', 'facebook-jssdk'));

but I have an error: "Uncaught Error: init not called with valid version " Was trying also other versions like: 2.1, 2.2 and still no luck. What am I doing wrong here?

但是我有一个错误:“未被捕获的错误:init没有调用有效版本”正在尝试其他版本,如:2.1,2.2,仍然没有运气。我在这里做错了什么?

17 个解决方案

#1


29  

**Disclaimer - This is purely speculation. Seems to have solved my problem.

**免责声明-这纯粹是猜测。似乎已经解决了我的问题。


I've had this issue on a recent project. I think this is a latency issue. The Facebook SDK requires that <div id="fb-root"></div> be on the page. This should be the first thing after the opening body tag. After this, you may see your initialization code.

我在最近的一个项目上遇到了这个问题。我认为这是一个潜在的问题。Facebook SDK要求

在页面上。这应该是第一个在打开的body标签之后。在此之后,您可以看到您的初始化代码。

For me, this issue was not consistent. I would occasionally see the bug and sometimes I would not. Thus, my conclusion of it being a latency problem. If the SDK cannot find the fb-root, then it must create one. Herein, is where I believe the latency issue exists.

对我来说,这个问题是不一致的。我偶尔会看到虫子,有时候我不会。因此,我的结论是它是一个延迟问题。如果SDK不能找到fb根,那么它必须创建一个。在这里,我认为存在延迟问题。

Try adding this just after your opening body tag, but before your FB.init({});.

尝试在您的打开body标签之后添加这个,但是在您的FB.init({})之前。

<div id="fb-root"></div>

This seems to have solved the issue for me and will hopefully help others as well. The v1.0 documentation discusses the reason for fb-root, but the v2.0 docs make no mention of the item, likely because the init script will add it for you if it does not find it.

这似乎解决了我的问题,也希望能帮助其他人。v1.0文档讨论了fb-root的原因,但是v2.0文档没有提到这个项目,很可能是因为init脚本会在没有找到它的情况下为您添加它。

#2


19  

I got it working by using all.js instead of sdk.js.
In your case, it would look like:

我用所有的方法让它工作。js代替sdk.js。在你的案例中,它看起来是这样的:

js.src = "//connect.facebook.net/pl_PL/all.js";

instead of

而不是

js.src = "//connect.facebook.net/pl_PL/sdk.js";

#3


11  

Add &version=v2.0 to js.src, as follows:

添加版本= v2.0 js。src,如下所示:

(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#xfbml=1&version=v2.0";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

#4


5  

This problem plagued me for a while. I tried many of the ideas listed here such as changing the version number and moving/removing the fb-root.

这个问题困扰了我一段时间。我尝试了许多在这里列出的想法,比如更改版本号和移动/删除fb-root。

What is finally working well for me is to delete the entire window.fbAsyncInit function and specify the init properties in the hash of sdk.js. For example:

对我来说,最后的工作是删除整个窗口。fbAsyncInit函数并在sdk.js的散列中指定init属性。例如:

<script type="text/javascript">
    (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 = "https://connect.facebook.net/en_US/sdk.js#version=v2.2&appId=12345&status=true&cookie=true&xfbml=true";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>

Of course you may omit a parameter to use its default value.

当然,您可以省略一个参数来使用它的默认值。

I can't find this approach documented anywhere so use it at your own risk. Luckily I was upgrading an older site from v1.x to v2.x and it used this technique when loading all.js.

我在任何地方都找不到这种方法,所以在你自己的风险中使用它。幸运的是,我从v1升级了一个老站点。x v2。在加载all.js时,它使用了这种技术。

#5


5  

i replaced this

我更换这个

js.src = "//connect.facebook.net/en_US/sdk.js";

with this

用这个

js.src = "//connect.facebook.net/en_US/all.js";

and worked :)

和工作:)

#6


3  

This was happening to me too with great inconsistency. Somewhere my hunch said, it is got to be a timing issue. Further debugging, found out an error in developer console by manually executing "FB.login()". The error said, "init not called with valid version".

这在我身上也发生了很大的不一致。我的直觉告诉我,这是一个时机问题。进一步的调试,通过手工执行“FB.login()”发现了开发人员控制台中的一个错误。错误说,“init没有调用有效的版本”。

In my case, I was adding //connect.facebook.net/en_US/sdk.js as a script tag in the header of the html page and the window.fbAsyncInit came in another file just after that. This pointed to me as a timing issue and hence I swapped these 2 script tags. Now once I had included window.fbAsyncInit before including //connect.facebook.net/en_US/sdk.js, the problem was gone. Hope this helps others.

在我的例子中,我在html页面和窗口的页眉中添加// connect.facebook.net/en_us/sdk.js作为脚本标记。在那之后,fbAsyncInit出现在另一个文件中。这将我作为一个计时问题,因此我交换了这两个脚本标签。有一次我把窗户都包括进去了。fbAsyncInit在包括// connect.facebook.net/en_us/sdk.jsse之前,问题已经解决了。希望这可以帮助别人。

#7


2  

This was the only fix that would eliminate the error 100% of the time.

这是唯一可以100%消除错误的方法。

You can recreate this error by deleting your FB.init. Which confirms that although the sdk.js had been loaded and the FB namespace existed, FB.init hadn't been called by the time we were trying to use FB methods elsewhere in our scripts.

您可以通过删除您的FB.init来重新创建这个错误。这证实了sdk的存在。js已经加载,FB命名空间也存在,FB。在我们尝试在脚本的其他地方使用FB方法时,init并没有被调用。

So we need to ensure that FB.init has been called. I used a similar approach to this answer:

所以我们需要确保FB。init被称为。我用了类似的方法来回答这个问题:

if (typeof(fbApi) === 'undefined') { fbApi = {}; }
fbApi = (function () {

    var fbApiInit = false;

    var awaitingReady = [];

    var notifyQ = function() {
        var i = 0,
            l = awaitingReady.length;
        for(i = 0; i < l; i++) {
            awaitingReady[i]();
        }
    };

    var ready = function(cb) {
        if (fbApiInit) {
            cb();
        } else {
            awaitingReady.push(cb);
        }
    };

    window.fbAsyncInit = function () {
      FB.init({
        appId  : '<?php echo esc_js( $facebook_app_id ); ?>',
        status : true,
        cookie : true,
        xfbml  : true,
        version: 'v2.0'
      });

      fbApiInit = true;
      notifyQ();
    };

    return {
        /**
         * Fires callback when FB is initialized and ready for api calls.
         */
        'ready': ready
    };

})();

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

Then, elsewhere, any reference to FB can be made like this:

然后,在其他地方,对FB的任何引用都可以这样做:

        fbApi.ready(function() {
          FB.XFBML.parse($("#fb-comments"));
        });

#8


1  

Try this code:

试试这段代码:

setInterval(
function() { FB.api('/me/', 
    function(r) { console.log('response: ', r); })
}, 5000);

I noticed then when I'm trying get info fb still be not initialized.

我注意到,当我尝试获取信息时,fb仍然没有初始化。

I fixed it by adding my initialization code to end of:

我将初始化代码添加到:

FB.getLoginStatus(function(response) { init(); });

#9


1  

I resolved this error by loading the script on document ready instead of document load.

我通过在准备文档时加载脚本而不是文档加载来解决这个错误。

For example, this gave the error about 10% of the time:

例如,这个误差大约为10%

$(window).load(function(){
  (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'));
});

whereas this works all the time:

而这种方法一直有效:

$(window).ready(function(){
  (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'));
});

#10


1  

Watch out when you call FB api after init. Init seems synchronous, but window.fbAsyncInit is not, so you have to wait for its execution. My example to reproduce is in phonegap browser platform, but after I checked the facebook plugin code I'm sure it can be reproduced in pure javascript environment also.

当你在init后调用FB api时要注意。Init似乎是同步的,但是是窗口。fbAsyncInit不是,所以你必须等待它的执行。我的例子是在phonegap浏览器平台上进行复制,但是在我检查了facebook的插件代码之后,我确信它也可以在纯javascript环境中复制。

This was my code that fires the error:

这是我的代码,它触发了错误:

if (window.config.debug_mode) {
    facebookConnectPlugin.browserInit('xxxxxxxxx', function() {
    });
}
// getLoginStatus is wrong here as window.fbAsyncInit is not yet completed
facebookConnectPlugin.getLoginStatus(function(status) {
    alert('logged: ' + JSON.stringify(status));
}, function(error) {
    alert('error: ' + JSON.stringify(error));
});

Here is how I fixed it:

我是这样修正的:

if (window.config.debug_mode) {
    facebookConnectPlugin.browserInit('xxxxxxxxx', function() {
        facebookConnectPlugin.getLoginStatus(function(status) {
            alert('logged: ' + JSON.stringify(status));
        }, function(error) {
            alert('error: ' + JSON.stringify(error));
        });
    });
}

I'm sure that the following code will throw in browser, but I don't have time to verify it:

我确信下面的代码会在浏览器中出现,但是我没有时间去验证它:

window.fbAsyncInit = function fbAsyncInit () {
    version = version || 'v2.6'

    FB.init({
        appId: appId,
        xfbml: false,
        version: version
    })
}
// now calling any FB function here will rise this error

#11


0  

We use our own API that does this:

我们使用自己的API:

   _loadFacebookApi: function(callback) {
        logger.info('_loadFacebookApi');

        (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 = "https://connect.facebook.net/en_US/sdk.js";


        }(document, 'script', 'facebook-jssdk'));

        var fbScript = window.document.getElementById('facebook-jssdk');

        fbScript.onload = fbScript.onreadystatechange = (function() {

            logger.info('fbScript onLoad');

            window.FB.init({
                version: 'v2.1',
                appId: '',
                channelUrl: '/fbchannel.html',
                status: false,
                cookie: true,
                xfbml: true,
                logging: true,
                oath: true
            });

            this.dispatch(constants.FACEBOOK_INIT_SUCCESS);

            if(callback){
                callback();
            }

        }.bind(this));

    }

#12


0  

I had the same problem when I tried to embed a simple Facebook post in an article I was writing.

当我试图在我写的文章中嵌入一个简单的Facebook帖子时,我遇到了同样的问题。

<div id="fb-root"></div><script>(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#xfbml=1&amp;version=v2.3";  fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk'));</script><div class="fb-post" data-href="https://www.facebook.com/feyenoord/posts/10153224326681816:0" data-width="500"><div class="fb-xfbml-parse-ignore"><blockquote cite="https://www.facebook.com/feyenoord/posts/10153224326681816:0"><p>Een teleurstellende middag in De Kuip. Ook ADO Den Haag bleek vanmiddag te sterk voor Feyenoord. http://bit.ly/1UA3ZxZADO Den Haag too strong for Feyenoord. http://bit.ly/1UA6rEN</p>Posted by <a href="https://www.facebook.com/feyenoord/">Feyenoord Rotterdam</a> on&nbsp;<a href="https://www.facebook.com/feyenoord/posts/10153224326681816:0">Sunday, January 31, 2016</a></blockquote></div></div>

When I debugged the Facebook sdk.js I saw that the .getVersion returned "undefined" and thus not rendering the widget.

当我调试Facebook sdk的时候。我看到. getversion返回了“未定义”,因此没有呈现小部件。

Apparently Facebook can't handle passing query parameters seperated by &amp; instead of & when loading the sdk.js. I had changed my code to &amp; for validation reasons.

显然,Facebook无法处理通过&amp分离的查询参数;而不是&加载sdk.js时。我已经把我的代码更改为&原因验证。

Works:        js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.3";
Doesn't Work: js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&amp;version=v2.3";

FB init函数给出错误的版本错误。

#13


0  

The error happened each time I redirected to a page (Edge Browser) that had a fb-page plugin.

每次我重定向到有一个fb-page插件的页面(Edge浏览器)时,都会发生错误。

If I refreshed the page it would work. If I got there through a hyperlink it would throw the error.

如果我刷新页面,它就会工作。如果我通过超链接到达那里,它会抛出错误。

Fixed it by adding sdk.js?d=" + new Date().toISOString(); to the script.

通过添加sdk.js来修复它?d = " +新日期(日).toISOString();脚本。

(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?d=" + new Date().toISOString();
        fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

#14


0  

You are using the cordova-plugin-facebook4 plugin, and that is a custom error message that means that the init hasn't finished when the facebook api function is called. Since the plugin does not give a waitForInitialize using setTimeout and then retrying the api method is the best bet.

您使用的是cordova-plugin-facebook4插件,这是一个自定义错误消息,这意味着在调用facebook api函数时,init还没有完成。由于插件没有使用setTimeout提供waitForInitialize,然后重新尝试api方法是最好的选择。

var retryFunc = (iteration) => {
    return new Promise((s, f) => facebookConnectPlugin.getLoginStatus(s, f))
    .then(authentication => authentication.status === 'connected')
    .then(isLoggedIn => {
        /* Your Code Here */
    })
    .catch(failure => {
        console.log(`Waiting for Facebook Init. Iteration: ${iteration || 0}`);
        if((iteration || 0) < 10) { 
            return new Promise((s, setTimeout(() => s(), 1000)
            .then(() => retryFunc(null, (iteration || 0) + 1);
        }
        else { return Promise.reject({Error: 'Failed to check login status.', Detail: failure}); }
    });
};

retryFunc();
/* Or replace getLoginStatus with your api call. */

#15


0  

SINGLE INCLUDE—make sure the Facebook JavaScript API isn't included more than once on your page.

单一的包含-确保Facebook JavaScript API不包含在你的页面上不止一次。

(This was my problem)

(这是我的问题)

#16


0  

Make sure you're using https:// in the URL

js.src = "https://connect.facebook.net/en_US/sdk.js";

I would not have believed this either, but the only difference between what Facebook has in their current sample code and what I have is https:// instead of // for the url.

我也不会相信这一点,但是Facebook现有的样例代码和我所拥有的唯一不同之处是https://而不是url。

Updating to be https:// seems to have fixed it for me and I cannot duplicate the error.

更新为https://似乎为我修复了它,我不能复制错误。

Also if you're doing any checks elsewhere in your code to see if FB is defined make sure to check if (window.FB) and not if (FB) or you will get an error.

另外,如果你在代码的其他地方做任何检查,看看FB是否被定义,确保检查(window.FB)而不是if (FB),或者你会得到错误。

// call after manually adding DOM nodes containing FB widgets
if (window.FB)
{
    window.FB.XFBML.parse()
}

If you're using typescript you need to add something like this:

如果你使用的是打字稿,你需要添加如下内容:

interface Window
{
    FB: IFacebook;
}

interface IFacebook
{
    XFBML: any;
    ui: any;
    getLoginStatus(callback: (response: { status: string }) => any);
    login(callback: (response) => any, options: any);
    logout(callback: () => any);
    Event: any;
    api(url: string, callback: (response: any) => any);
}

#17


-3  

window.fbAsyncInit = function() {
    FB.init({
      appId      : 'xxxx', // App ID
      status     : false, 
      version:  'v2.0',
      cookie     : true, 
      xfbml      : false  // parse XFBML
    });
};

There is error version: 'v2.0', This is not valid code

有错误版本:“v2.0”,这不是有效的代码。

#1


29  

**Disclaimer - This is purely speculation. Seems to have solved my problem.

**免责声明-这纯粹是猜测。似乎已经解决了我的问题。


I've had this issue on a recent project. I think this is a latency issue. The Facebook SDK requires that <div id="fb-root"></div> be on the page. This should be the first thing after the opening body tag. After this, you may see your initialization code.

我在最近的一个项目上遇到了这个问题。我认为这是一个潜在的问题。Facebook SDK要求

在页面上。这应该是第一个在打开的body标签之后。在此之后,您可以看到您的初始化代码。

For me, this issue was not consistent. I would occasionally see the bug and sometimes I would not. Thus, my conclusion of it being a latency problem. If the SDK cannot find the fb-root, then it must create one. Herein, is where I believe the latency issue exists.

对我来说,这个问题是不一致的。我偶尔会看到虫子,有时候我不会。因此,我的结论是它是一个延迟问题。如果SDK不能找到fb根,那么它必须创建一个。在这里,我认为存在延迟问题。

Try adding this just after your opening body tag, but before your FB.init({});.

尝试在您的打开body标签之后添加这个,但是在您的FB.init({})之前。

<div id="fb-root"></div>

This seems to have solved the issue for me and will hopefully help others as well. The v1.0 documentation discusses the reason for fb-root, but the v2.0 docs make no mention of the item, likely because the init script will add it for you if it does not find it.

这似乎解决了我的问题,也希望能帮助其他人。v1.0文档讨论了fb-root的原因,但是v2.0文档没有提到这个项目,很可能是因为init脚本会在没有找到它的情况下为您添加它。

#2


19  

I got it working by using all.js instead of sdk.js.
In your case, it would look like:

我用所有的方法让它工作。js代替sdk.js。在你的案例中,它看起来是这样的:

js.src = "//connect.facebook.net/pl_PL/all.js";

instead of

而不是

js.src = "//connect.facebook.net/pl_PL/sdk.js";

#3


11  

Add &version=v2.0 to js.src, as follows:

添加版本= v2.0 js。src,如下所示:

(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#xfbml=1&version=v2.0";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

#4


5  

This problem plagued me for a while. I tried many of the ideas listed here such as changing the version number and moving/removing the fb-root.

这个问题困扰了我一段时间。我尝试了许多在这里列出的想法,比如更改版本号和移动/删除fb-root。

What is finally working well for me is to delete the entire window.fbAsyncInit function and specify the init properties in the hash of sdk.js. For example:

对我来说,最后的工作是删除整个窗口。fbAsyncInit函数并在sdk.js的散列中指定init属性。例如:

<script type="text/javascript">
    (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 = "https://connect.facebook.net/en_US/sdk.js#version=v2.2&appId=12345&status=true&cookie=true&xfbml=true";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>

Of course you may omit a parameter to use its default value.

当然,您可以省略一个参数来使用它的默认值。

I can't find this approach documented anywhere so use it at your own risk. Luckily I was upgrading an older site from v1.x to v2.x and it used this technique when loading all.js.

我在任何地方都找不到这种方法,所以在你自己的风险中使用它。幸运的是,我从v1升级了一个老站点。x v2。在加载all.js时,它使用了这种技术。

#5


5  

i replaced this

我更换这个

js.src = "//connect.facebook.net/en_US/sdk.js";

with this

用这个

js.src = "//connect.facebook.net/en_US/all.js";

and worked :)

和工作:)

#6


3  

This was happening to me too with great inconsistency. Somewhere my hunch said, it is got to be a timing issue. Further debugging, found out an error in developer console by manually executing "FB.login()". The error said, "init not called with valid version".

这在我身上也发生了很大的不一致。我的直觉告诉我,这是一个时机问题。进一步的调试,通过手工执行“FB.login()”发现了开发人员控制台中的一个错误。错误说,“init没有调用有效的版本”。

In my case, I was adding //connect.facebook.net/en_US/sdk.js as a script tag in the header of the html page and the window.fbAsyncInit came in another file just after that. This pointed to me as a timing issue and hence I swapped these 2 script tags. Now once I had included window.fbAsyncInit before including //connect.facebook.net/en_US/sdk.js, the problem was gone. Hope this helps others.

在我的例子中,我在html页面和窗口的页眉中添加// connect.facebook.net/en_us/sdk.js作为脚本标记。在那之后,fbAsyncInit出现在另一个文件中。这将我作为一个计时问题,因此我交换了这两个脚本标签。有一次我把窗户都包括进去了。fbAsyncInit在包括// connect.facebook.net/en_us/sdk.jsse之前,问题已经解决了。希望这可以帮助别人。

#7


2  

This was the only fix that would eliminate the error 100% of the time.

这是唯一可以100%消除错误的方法。

You can recreate this error by deleting your FB.init. Which confirms that although the sdk.js had been loaded and the FB namespace existed, FB.init hadn't been called by the time we were trying to use FB methods elsewhere in our scripts.

您可以通过删除您的FB.init来重新创建这个错误。这证实了sdk的存在。js已经加载,FB命名空间也存在,FB。在我们尝试在脚本的其他地方使用FB方法时,init并没有被调用。

So we need to ensure that FB.init has been called. I used a similar approach to this answer:

所以我们需要确保FB。init被称为。我用了类似的方法来回答这个问题:

if (typeof(fbApi) === 'undefined') { fbApi = {}; }
fbApi = (function () {

    var fbApiInit = false;

    var awaitingReady = [];

    var notifyQ = function() {
        var i = 0,
            l = awaitingReady.length;
        for(i = 0; i < l; i++) {
            awaitingReady[i]();
        }
    };

    var ready = function(cb) {
        if (fbApiInit) {
            cb();
        } else {
            awaitingReady.push(cb);
        }
    };

    window.fbAsyncInit = function () {
      FB.init({
        appId  : '<?php echo esc_js( $facebook_app_id ); ?>',
        status : true,
        cookie : true,
        xfbml  : true,
        version: 'v2.0'
      });

      fbApiInit = true;
      notifyQ();
    };

    return {
        /**
         * Fires callback when FB is initialized and ready for api calls.
         */
        'ready': ready
    };

})();

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

Then, elsewhere, any reference to FB can be made like this:

然后,在其他地方,对FB的任何引用都可以这样做:

        fbApi.ready(function() {
          FB.XFBML.parse($("#fb-comments"));
        });

#8


1  

Try this code:

试试这段代码:

setInterval(
function() { FB.api('/me/', 
    function(r) { console.log('response: ', r); })
}, 5000);

I noticed then when I'm trying get info fb still be not initialized.

我注意到,当我尝试获取信息时,fb仍然没有初始化。

I fixed it by adding my initialization code to end of:

我将初始化代码添加到:

FB.getLoginStatus(function(response) { init(); });

#9


1  

I resolved this error by loading the script on document ready instead of document load.

我通过在准备文档时加载脚本而不是文档加载来解决这个错误。

For example, this gave the error about 10% of the time:

例如,这个误差大约为10%

$(window).load(function(){
  (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'));
});

whereas this works all the time:

而这种方法一直有效:

$(window).ready(function(){
  (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'));
});

#10


1  

Watch out when you call FB api after init. Init seems synchronous, but window.fbAsyncInit is not, so you have to wait for its execution. My example to reproduce is in phonegap browser platform, but after I checked the facebook plugin code I'm sure it can be reproduced in pure javascript environment also.

当你在init后调用FB api时要注意。Init似乎是同步的,但是是窗口。fbAsyncInit不是,所以你必须等待它的执行。我的例子是在phonegap浏览器平台上进行复制,但是在我检查了facebook的插件代码之后,我确信它也可以在纯javascript环境中复制。

This was my code that fires the error:

这是我的代码,它触发了错误:

if (window.config.debug_mode) {
    facebookConnectPlugin.browserInit('xxxxxxxxx', function() {
    });
}
// getLoginStatus is wrong here as window.fbAsyncInit is not yet completed
facebookConnectPlugin.getLoginStatus(function(status) {
    alert('logged: ' + JSON.stringify(status));
}, function(error) {
    alert('error: ' + JSON.stringify(error));
});

Here is how I fixed it:

我是这样修正的:

if (window.config.debug_mode) {
    facebookConnectPlugin.browserInit('xxxxxxxxx', function() {
        facebookConnectPlugin.getLoginStatus(function(status) {
            alert('logged: ' + JSON.stringify(status));
        }, function(error) {
            alert('error: ' + JSON.stringify(error));
        });
    });
}

I'm sure that the following code will throw in browser, but I don't have time to verify it:

我确信下面的代码会在浏览器中出现,但是我没有时间去验证它:

window.fbAsyncInit = function fbAsyncInit () {
    version = version || 'v2.6'

    FB.init({
        appId: appId,
        xfbml: false,
        version: version
    })
}
// now calling any FB function here will rise this error

#11


0  

We use our own API that does this:

我们使用自己的API:

   _loadFacebookApi: function(callback) {
        logger.info('_loadFacebookApi');

        (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 = "https://connect.facebook.net/en_US/sdk.js";


        }(document, 'script', 'facebook-jssdk'));

        var fbScript = window.document.getElementById('facebook-jssdk');

        fbScript.onload = fbScript.onreadystatechange = (function() {

            logger.info('fbScript onLoad');

            window.FB.init({
                version: 'v2.1',
                appId: '',
                channelUrl: '/fbchannel.html',
                status: false,
                cookie: true,
                xfbml: true,
                logging: true,
                oath: true
            });

            this.dispatch(constants.FACEBOOK_INIT_SUCCESS);

            if(callback){
                callback();
            }

        }.bind(this));

    }

#12


0  

I had the same problem when I tried to embed a simple Facebook post in an article I was writing.

当我试图在我写的文章中嵌入一个简单的Facebook帖子时,我遇到了同样的问题。

<div id="fb-root"></div><script>(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#xfbml=1&amp;version=v2.3";  fjs.parentNode.insertBefore(js, fjs);}(document, 'script', 'facebook-jssdk'));</script><div class="fb-post" data-href="https://www.facebook.com/feyenoord/posts/10153224326681816:0" data-width="500"><div class="fb-xfbml-parse-ignore"><blockquote cite="https://www.facebook.com/feyenoord/posts/10153224326681816:0"><p>Een teleurstellende middag in De Kuip. Ook ADO Den Haag bleek vanmiddag te sterk voor Feyenoord. http://bit.ly/1UA3ZxZADO Den Haag too strong for Feyenoord. http://bit.ly/1UA6rEN</p>Posted by <a href="https://www.facebook.com/feyenoord/">Feyenoord Rotterdam</a> on&nbsp;<a href="https://www.facebook.com/feyenoord/posts/10153224326681816:0">Sunday, January 31, 2016</a></blockquote></div></div>

When I debugged the Facebook sdk.js I saw that the .getVersion returned "undefined" and thus not rendering the widget.

当我调试Facebook sdk的时候。我看到. getversion返回了“未定义”,因此没有呈现小部件。

Apparently Facebook can't handle passing query parameters seperated by &amp; instead of & when loading the sdk.js. I had changed my code to &amp; for validation reasons.

显然,Facebook无法处理通过&amp分离的查询参数;而不是&加载sdk.js时。我已经把我的代码更改为&原因验证。

Works:        js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.3";
Doesn't Work: js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&amp;version=v2.3";

FB init函数给出错误的版本错误。

#13


0  

The error happened each time I redirected to a page (Edge Browser) that had a fb-page plugin.

每次我重定向到有一个fb-page插件的页面(Edge浏览器)时,都会发生错误。

If I refreshed the page it would work. If I got there through a hyperlink it would throw the error.

如果我刷新页面,它就会工作。如果我通过超链接到达那里,它会抛出错误。

Fixed it by adding sdk.js?d=" + new Date().toISOString(); to the script.

通过添加sdk.js来修复它?d = " +新日期(日).toISOString();脚本。

(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?d=" + new Date().toISOString();
        fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

#14


0  

You are using the cordova-plugin-facebook4 plugin, and that is a custom error message that means that the init hasn't finished when the facebook api function is called. Since the plugin does not give a waitForInitialize using setTimeout and then retrying the api method is the best bet.

您使用的是cordova-plugin-facebook4插件,这是一个自定义错误消息,这意味着在调用facebook api函数时,init还没有完成。由于插件没有使用setTimeout提供waitForInitialize,然后重新尝试api方法是最好的选择。

var retryFunc = (iteration) => {
    return new Promise((s, f) => facebookConnectPlugin.getLoginStatus(s, f))
    .then(authentication => authentication.status === 'connected')
    .then(isLoggedIn => {
        /* Your Code Here */
    })
    .catch(failure => {
        console.log(`Waiting for Facebook Init. Iteration: ${iteration || 0}`);
        if((iteration || 0) < 10) { 
            return new Promise((s, setTimeout(() => s(), 1000)
            .then(() => retryFunc(null, (iteration || 0) + 1);
        }
        else { return Promise.reject({Error: 'Failed to check login status.', Detail: failure}); }
    });
};

retryFunc();
/* Or replace getLoginStatus with your api call. */

#15


0  

SINGLE INCLUDE—make sure the Facebook JavaScript API isn't included more than once on your page.

单一的包含-确保Facebook JavaScript API不包含在你的页面上不止一次。

(This was my problem)

(这是我的问题)

#16


0  

Make sure you're using https:// in the URL

js.src = "https://connect.facebook.net/en_US/sdk.js";

I would not have believed this either, but the only difference between what Facebook has in their current sample code and what I have is https:// instead of // for the url.

我也不会相信这一点,但是Facebook现有的样例代码和我所拥有的唯一不同之处是https://而不是url。

Updating to be https:// seems to have fixed it for me and I cannot duplicate the error.

更新为https://似乎为我修复了它,我不能复制错误。

Also if you're doing any checks elsewhere in your code to see if FB is defined make sure to check if (window.FB) and not if (FB) or you will get an error.

另外,如果你在代码的其他地方做任何检查,看看FB是否被定义,确保检查(window.FB)而不是if (FB),或者你会得到错误。

// call after manually adding DOM nodes containing FB widgets
if (window.FB)
{
    window.FB.XFBML.parse()
}

If you're using typescript you need to add something like this:

如果你使用的是打字稿,你需要添加如下内容:

interface Window
{
    FB: IFacebook;
}

interface IFacebook
{
    XFBML: any;
    ui: any;
    getLoginStatus(callback: (response: { status: string }) => any);
    login(callback: (response) => any, options: any);
    logout(callback: () => any);
    Event: any;
    api(url: string, callback: (response: any) => any);
}

#17


-3  

window.fbAsyncInit = function() {
    FB.init({
      appId      : 'xxxx', // App ID
      status     : false, 
      version:  'v2.0',
      cookie     : true, 
      xfbml      : false  // parse XFBML
    });
};

There is error version: 'v2.0', This is not valid code

有错误版本:“v2.0”,这不是有效的代码。