2016-10-05 00:00:00

Applying meta facebook share on ASP .NET control

Here I want to explain how to customize facebook share. My problem was how to apply dynamic content eg. blog titles/images on facebook share dialog.

First thing - be patient. I know there are many problems with facebook api and their documentation is clear only for writers.

After reading documentation you need to create a facebook app to get facebook app ID. I'll mention this at beginning - remember to publish app (if it's ready to publish) because you won't be able to share anything and you waste hours like me :)

After creating an app you can go to "chare button creator". Here you need to pick an application and then type an url to share. No worries, you can type anything because we will change it on runtime via asp.net/javascript. Okay, your share button content (let's call it SBC) is ready and you can copy code to paste on website. To corrrectly copy you will have to do few steps.
1. Create an ContentPlaceHolder somewhere in masterpage. Here you will apply metas which will describe your share content.
2. In page (in my case BlogPage.aspx) you will need to add all metas from SBC. to metas which will need update you will need to add ID and runat="server".
3. In codebehind (BlogPage.aspx.cs) you can edit values using Atrributes collection property eg. urlMeta.Attributes["content"] = Request.RawUrl;
4. Okay, metas ready, now time to include the rest of SBC content. As facebook suggest I also suggest creating new ContentPlaceHolder at the beginning in body tag and in this placeholder I would insert script code from SBC.
5. In SBC we have button code. You will need to paste it and edit via javascript to fit any of blog posts. I am using method:

   script type="text/javascript">

        window.addEventListener('load', load, false);

//apply new share link
        function load() {
            var url = window.location;
            document.getElementsByClassName('fb-share-button')[0].setAttribute('data-href', url);

//also replace share href
        function fbshareCurrentPage() {// to apply inside href attribute of  link 
            window.open("https://www.facebook.com/sharer/sharer.php?u=" + escape(window.location) + "&t=" + document.title, '',
            return false;

6. That's all. We need to run it and WAIT. The changes need few mins to apply. Please notice that you won't be able to test everything on localhost so it's good to have 2 servers - one for production and second for final website version.