简体   繁体   中英

Call FB.ui only after clicking on the fb.share button

What I'm trying to achieve is:

I have a simple facebook share button taken from facebook dev. site:

<div class="fb-share-button" data-layout="button_count"></div>

Now I added the facebook app code also taken from facebook just before the opening body tag:

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

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

Now I added this FB.ui script below the facebook share button:

FB.ui(
{
method: 'share',
href: document.URL,
},
function(response) {
if (response && !response.error_code) {
  alert('Posting completed.');
} else {
  alert('Error while posting.');
}
}
);

The problem at the moment is that as soon as the page loads the facebook share is automatically triggered and everything works correctly, but, what I want is that the facebook share to appear (and the FB.ui to work) only when the user presses the facebook share button and not automatically. Can someone please help me with this?

You can run the FB.ui code when you click on the button with a class of fb-share-button using jQuery:

$(".fb-share-button').click(function(){
    //here goes the FB.ui function
    FB.ui(
    {
        method: 'share',
        href: document.URL,
    },
    function(response) {
        if (response && !response.error_code) {
          alert('Posting completed.');
        } else {
          alert('Error while posting.');
        }
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM