Make my own custom Facebook share button

Andreas picture Andreas · May 14, 2015 · Viewed 7.3k times · Source

I'm pretty (below) average when it comes to HTML/CSS-coding. My Javascript knowledge is at the copy-and-paste level. This is my problem:

I want to make my own Facebook share-button! It used to be simple with sharer.php, but I'm afraid it will be deprecated. So I want to trigger the share dialog with a link of my own, instead of using Facebooks own ugly share button plugin.

I've read the page about the Share Dialog on Facebook Developers. But I don't understand how/where to use the code snippets. To be honest I understand nothing. Nothing!

To make it simple, let's say I have my own button (button.jpg) and I want this button to open the Facebook share dialog to share the page URL (http://example.com). I have meta Open Graph tags. How do I do this?

Answer

luschn picture luschn · May 14, 2015

sharer.php is not deprecated (at least not anymore), you can use it without any problem.

Anyway, the Share Button is easy to implement. You just need to load/initialize the JavaScript SDK and call FB.ui on click.

JavaScript SDK: https://developers.facebook.com/docs/javascript/quickstart/v2.3

Share Dialog: https://developers.facebook.com/docs/sharing/reference/share-dialog

For example:

<script>
    function onClick() {
        FB.ui({
            method: 'share',
            href: 'https://www.your-url.com',
        });
    }

    window.fbAsyncInit = function() {
        FB.init({
            appId      : 'your-app-id',
            xfbml      : true,
            version    : 'v2.3'
        });
    };

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