How to add Facebook Share Button to the Page

2016/1/317 min read
bookmark this
Responsive image

Nowaday, lots of website are using facebook share module, this blog will show few ways of how to implement facebook share, they can use by different scenrio and level of web skill.

1. Use Default Facebook Share button

Following is few things you need to do for use the default facebook share button.

Go to Facebook Share Developer Page, check the code, but following is the example how I'm doing it.

Facebook SDK + custom Js module for facebook share

You need Facebook SDK for facebook share, without this the share won't work, you cn get this javascript from facebook developer page.

The second thing i'm doing here, depend on my page add current page's url to the html, so when share the page, facebook share would know you shared which page.


/*
 * Javascript SDK from Facebook.
 */
(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.5";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

/*
 * facebook shared
 * html
 * 
 */
var dhe = dhe || {};
dhe.fb_share = (function () {
    var fbData = document.querySelector('.fb-share-button');
    fbData.dataset.href = window.location.pathname;
    return {};
})();

The Html


<a class="fb-share-button" data-href='' data-layout='button_count'></a>

Buttons looks like following

Meta Tag

This meta tag is also important, because when you use default facebook share, the share window will use following information to display, such as image, description, title.


    <meta property="og:url" content="/blog/post/javascript-ecmascript-5">
    <meta property="og:type" content="Hack The Web">
    <meta property="og:description" content="Hack The Web - Javascript (ECMAScript) 5">
    <meta property="og:image" content="https://d1p0mp3f1fx0hz.cloudfront.net/_3reqj4osr.png">
    <meta property="og:image:type" content="image/png">
    <meta property="og:image:width" content="256">
    <meta property="og:image:height" content="256">
    <meta property="og:title" content="Javascript (ECMAScript) 5">

Conclusions

I think this default facebook share is good for starter, easy to implement the share feature. However it is less flexbility. If you have multi share at the same page, they all going to use same picture, title. Also, it is hard to change the style.

2. Facebook share - Control the UI

The following solution is more flexible, because you have totally control the UI looks, also you can get how many total shared from the specific page, use the total shared to control the UI as well. Now, following are steps how you do it.

First, Let me show how's the result looks first, follwing is using the FontAwesome icon.

Sounds like you have full control of the facebook share, however you're depend on following two api. First one, graph.facebook, you can get the total share and comments from the api by passing your page. Second url provide facebook share feature by passing defined parameter, such as u is the actual url of your page. Also, it'll depend on your Metatag. You still depend on these two url, and it's hard to find how many parameter they support, because document is poor.


http://graph.facebook.com/
https://www.facebook.com/sharer/sharer.php?u={encoded url}&t={title, seperate by + }

Following are the code i did at javascript.

Following facebook share could do the same facebook share feature, also you could get the count of the share for the page.

/*
 * Javascript SDK from Facebook.
 */
(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.5&title=test";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

/*
 * My own customized js code
 */
var dhe = dhe || {};
dhe.fb_share = (function () {
    function openPopup(url) {
        window.open(url, "myWindow", "status = 1, height = 500, width = 500, resizable = 0")
    }
    
    function loadFBCount(url) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                //{
                //    "id": "http://news.ycombinator.com",
                //    "shares": 8868,
                //    "comments": 3
                //}
                return JSON.parse(xhttp.responseText);
            }
        };
        xhttp.open("GET", "http://graph.facebook.com/" + url, true);
        xhttp.send();
    }
    
    function init(){
        updateShare();
        var fbCount = loadFBCount(window.location.href);
        // update fb count to UI;
    }
    
    function updateShare(){
        var fbData = document.querySelector('.fb_share');
        var url = 'https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(window.location.href);
        fbData.href = "javascript:dhe.fb_share.openPopup('" + url + "')";
    }
    
    init();

    return {
        openPopup : openPopup
    };
})();

Html is as following, instead of font-awesome's icon, you could change to image or other resource.

<a href="" target="_blank" class="fb_share"><i class="fa fa-facebook-official"> </i></a>

Conclusions

Doing this way, you have full control of UI which how facebook should looks like, and able to get the total share. However it is still hard to control the shared window's content. Good things is, you don't need Facebook development account, for both above solution you can just copy javascript, copy html and you're done.

2. Facebook Feed Dialog

Facebook feed dialog is more flexiable compare to the first two, first you need to go to facebook developer to register and get app_id.

Once you got app_id you can start to use, following is how I'm doing.

 

Following is the result view.

 

Facebook SDK and APP init


/*
 * facebook SDK
 */
(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'));

/*
 * facebook APP init
 */
window.fbAsyncInit = function () {
    FB.init({
        appId      : 'your facebook app id',
        xfbml      : true,
        version    : 'v2.5'
    });
};

Following javascript, basically I'm bind the click event, and also provide method to get share url's total count.



/*
 * Use facebook.com/sharer/sharer.php and graph.facebook.com/
 */
var dhe = dhe || {};
dhe.fb_share2 = (function () {
    /*
     * 
     * return following type of json object.
    * {
    *     "id": "http://news.ycombinator.com",
    *     "shares": 8868,
    *     "comments": 3
    * }
     */
    function loadFBCount(url, updateCallBack) {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                updateCallBack(JSON.parse(xhttp.responseText));
            }
        };
        xhttp.open("GET", "http://graph.facebook.com/" + url, true);
        xhttp.send();
    }
    
    /*
     * update fb fshare count to UI
     */
    function updateCount(fbCount) {
        var fbShare = document.querySelector(".soc_count.fb");
        if (fbShare) {
            fbShare.innerHTML = fbCount.shares;
        }
    }
    
    /*
     * get current url, remove the hash or querystring
     */
    function GetCurrentUrl(){
        var _location = window.location;
        return _location.origin + _location.pathname;
    }
    
    /*
     * bind click event for facebook share
     * load facebook total count
     */
    function init() {
        var all = document.querySelectorAll(".dhe_fb_share");
        for (var i = 0; i < all.length; i++) {
            all[i].onclick = fbShareEvent;
        };
        
        loadFBCount(encodeURIComponent(GetCurrentUrl()), updateCount);
    }
    
    /*
     * get meta tag
     */
    function getMetaTag(tagName){
        var metas = document.getElementsByTagName('meta');
        for (i = 0; i < metas.length; i++) {
            if (metas[i].getAttribute("property") == tagName) {
                return metas[i].getAttribute("content");
            }
        }
    }
    
    /*
     * facebook share event
     */
    function fbShareEvent(e){
        var _this = this;
        var data = {};
        data["app_id"] = "Your Facebook APPID";

        data["method"] = "feed";
        data["href"] = _this.dataset.href ? encodeURIComponent(_this.dataset.href) : encodeURIComponent(GetCurrentUrl());
        data["caption"] = (_this.dataset.caption) ? _this.dataset.caption : getMetaTag("og:title");
        data["name"] = (_this.dataset.name) ? _this.dataset.name : getMetaTag("og:type");
        data["description"] = (_this.dataset.description) ? _this.dataset.description : getMetaTag("og:description");
        data["picture"] = (_this.dataset.picture) ? _this.dataset.picture : getMetaTag("og:image");
        if (_this.dataset.redirect_uri) {
            data["redirect_uri"] = _this.dataset.redirect_uri;
        }
        console.info(data);
        FB.ui(data, function (response) {
            console.info(response);
        });
    }
    
    init();
    
    return {
        loadFBCount : loadFBCount
    };
})();

HTML - following is example html

The way I'm trying to build is, following is minimal require fields, if html doesn't provide any value, default will go to meta tag to get the one. If you provide from html then will get from the html when click share.


<a href="#" class="soc-facebook dhe_fb_share"></a>

That says, if you define following at your html that would be show to the share window too.


<a href="#" data-href="http://www.dakehe.info/blog/post/facebook-share-button" data-caption="An example caption" data-picture="http://g-ecx.images-amazon.com/images/G/01/img16/events/valentine/31780_events_vday2016_gw-double-promo_440x200._CB300695157_.jpg" data-description="description" data-name="name" data-redirect_uri="http://www.dakehe.info" class="soc-facebook dhe_fb_share"></a>
<a href="#" data-href="http://www.dakehe.info/blog/post/facebook-share-button" data-caption="An example caption" data-description="description" data-name="name" data-redirect_uri="http://www.dakehe.info" class="soc-facebook dhe_fb_share"></a><a href="#" class="soc-facebook dhe_fb_share"></a>

Conclusion

If you're less knowledge of Javascript, you can try #1 to add facebook share, and if know javascript and the page you need facebook doesn't require much flexibility, you can use #2, but if your webpage need more than one facebook share, you can try #3.

More to come