Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

javascript - Vuejs component wait for facebook sdk to load

I have a component that show a login button or username of the user from facebook. depends if he is logged in or not.

Now in this component I use the

created

event so I'll check the login immidiatly. code in created in a brief:

FB.getLoginStatus(function(response) {
    //more things.....

the error is that it says that FB is not defined, and sure he is right, FB is not loaded yet.

I load facebook like this

<body>
<script>
  window.fbAsyncInit = function() {
  FB.init({
    appId      : '1111111111',
    xfbml      : true,
    version    : 'v2.7'
  });
};

(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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I was searching forever for a answer to this.

Thanx to vbranden's comment I was able to get it working for me.

What you have to do is initialise the facebook sdk in the created method. Then call the login from inside the fbAsyncInit function.

Here's what worked for me:

<body>
<div id="test"></div>

<script>
new Vue({
  el: '#test',
  created: function() {
    console.log('created main');
    window.fbAsyncInit = function() {
      FB.init({
        appId      : '1111111111',
        xfbml      : true,
        version    : 'v2.7'
      });

      //This function should be here, inside window.fbAsyncInit
      FB.getLoginStatus(function(response) {
        console.log(response);
     });

   };

    (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>
</body>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...