How to Add Facebook Share Button to the Page

2016/01/317 min read
bookmark this
Responsive image

Table of Contents

  1. Use Default Facebook Share Button
  2. Facebook Share - Control the UI
  3. Facebook Feed Dialog
  4. More to Come

Share Example 1 Share Example 2

Introduction

Nowadays, lots of websites are using the Facebook share module. This blog will show a few ways of how to implement Facebook share. They can be used for different scenarios and levels of web skill.

1. Use Default Facebook Share Button

Following are a few things you need to do to use the default Facebook share button.

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

Facebook SDK + Custom JS Module for Facebook Share

You need the Facebook SDK for Facebook share. Without this, the share won't work. You can get this JavaScript from the Facebook developer page.

The second thing I'm doing here is, depending on my page, adding the current page's URL to the HTML, so when sharing the page, Facebook share would know which page you shared.

/*
 * 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

Buttons Look Like the Following

Meta Tag

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









Conclusions

I think this default Facebook share is good for starters and is easy to implement as a share feature. However, it is less flexible. If you have multiple shares on the same page, they are all going to use the same picture and title. Also, it is hard to change the style.

2. Facebook Share - Control the UI

The following solution is more flexible because you have total control over how the UI looks. Also, you can get how many total shares there are from a specific page and use the total shared count to control the UI as well. Following are the steps for how to do it.

First, let me show how the result looks. The following is using the FontAwesome icon.

It sounds like you have full control of the Facebook share. However, you depend on the following two APIs. The first one, graph.facebook, lets you get the total shares and comments from the API by passing your page. The second URL provides the Facebook share feature by passing defined parameters, such as u which is the actual URL of your page. Also, it depends on your meta tag. You still depend on these two URLs, and it's hard to find how many parameters they support because documentation is poor.

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

Following is the code I wrote in JavaScript.

The following Facebook share can do the same Facebook share feature, and you can also get the count of shares 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
    };
})();

The HTML is as following. Instead of FontAwesome's icon, you could change it to an image or other resource.

[* *]()

Conclusions

Doing it this way, you have full control of the UI and how Facebook share should look, and you are able to get the total share count. However, it is still hard to control the shared window's content. The good thing is you don't need a Facebook developer account. For both of the above solutions, you can just copy the JavaScript, copy the HTML, and you're done.

3. Facebook Feed Dialog

The Facebook Feed Dialog is more flexible compared to the first two. First, you need to go to Facebook Developer to register and get an app_id.

Once you have the app_id, you can start using it. Following is how I'm doing it.

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

Click Event and Share Count

The following JavaScript basically binds the click event and also provides a method to get the 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 Example

The way I'm trying to build this is: the following shows the minimum required fields. If the HTML doesn't provide any value, the default will fall back to the meta tag. If you provide values from HTML, then they will be used when clicking share.



That said, if you define the following in your HTML, it would be shown in the share window too.

[](#)
[](#)[](#)

Conclusion

If you have less knowledge of JavaScript, you can try option #1 to add Facebook share. If you know JavaScript and the page you need doesn't require much flexibility, you can use #2. But if your webpage needs more than one Facebook share button, you can try #3.

More to Come

  • Facebook Developer - The Facebook developer page is a giant area containing lots of products. I'll try some of them and will write about them here.

  • Facebook debug tools