Facebook Javascript API : Feed and Share Dialog for Beginners

I received five emails last month especially from students on making their websites social.  This post is for them and all others who are interested in social media programming. Facebook Graph API no doubt is a silver bullet and a primary way today that allows us to post and retrieve data from-to Facebook. I am using it since its inception. I must say it is amazing and easy to work with.

This post is all about an interesting Facebook dialog which is powerful and has potential to generate decent traffic for your webpages. If you are a webmaster or an app developer, this post is for you.

Facebook dialogs are cool because they do not require any additional permissions as each one do not require someone to directly interact with them. Facebook offers dialogs for various purposes. I will write about each one of them in coming days. This post will give an introduction to Feed and Share dialog to begin with.

Feed and Share Dialog

Feed dialog allows users to post a story on their/others timeline (Well, after you login). The dialog works even on IOS & Android mobile platforms with a little variation in implementation. In the phone world, we call the same feed dialog as a Share Dialog. Here is how it looks. You might have come across this dialog while browsing websites or when using social media plugins on the blogs yourself.

Javascript Implementation : The fastest way

Idea : Let us have a screen with a login button. Clicking on it should allow a user to login through his facebook credentials. After successful login, our application must show another button, clicking on which would launch the Facebook Feed dialog. Our code should decide what to display in the dialog.

  • Open Visual Studio, create a new website by name "FBPlayground". Right click on the website name in the solution explorer and add a new html file "FeedAndShare.html".
  • Open the new file you just created and clear the contents of it. Add the below code, and save it.
       
<!DOCTYPE html>
<html>
<head>
    <title>Feed and Share Dialog</title>
    <script type="text/javascript" language="javascript">

        //Not Jquery !!! just a helper function to return an object
        function $(i_obj) {
            return document.getElementById(i_obj);
        }

        window.fbAsyncInit = function () {
            FB.init({
                appId: '757846120912141', // App ID : Insert the APP ID of the APP you created here
                status: true,
            });
        }


        function fbLogin() {
            FB.login(function (response) {
                if (response.status == "connected") {
                    //User has logged in, hide the login button and show the launch button

                    $("btnlogin").className = "Hide";
                    $("btnlauncher").className = "Show";

                } else {
                    // user has not yet logged in, hide launcher button and display login button

                    $("btnlogin").className = "Show";
                    $("btnlauncher").className = "Hide";
                }
            });
        }

        //Function displays the Feed Dialog
        function LaunchFeedDialog() {
        
        //Create an object with the below properties.
//There are a lot more parameters than what I have written below. Will explain each one of them in coming posts.
            var obj = {
                method: 'feed',
                link: 'www.msguy.com',
                picture: 'http://fbrell.com/f8.jpg',
                name: 'A Title for Feed Dialog',
                caption: 'Some Caption for the URL',
                description: 'A description for the URL which is to be displayed'
            };

            //Calling the Facebook API : Important
            FB.ui(obj, callback);
        }

        function callback(response) {
            //Do anything you want here :)
            //document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
            //alert(response['post_id']); Some diagnostics lol :)
        }

        // Load the SDK Asynchronously. This is a very important part. It loads the Facebook javascript SDK automatically.
        (function (d) {
            var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
            if (d.getElementById(id)) { return; }
            js = d.createElement('script'); js.id = id; js.async = true;
            js.src = "//connect.facebook.net/en_US/all.js";
            ref.parentNode.insertBefore(js, ref);
        } (document));
    </script>

    <!--Styles -->
    <style type="text/css">
        /*Hides a element*/
        .Hide
        {
            display: none;
        }
        
        /*Shows an element*/
        .Show
        {
            display: block;
        }
    </style>
</head>
<body>
    <!--User can click on this button and the fbLogin method is invoked which prompts for facebook login-->
    <input id="btnlogin" type="button" onclick="fbLogin()" value="Login with Facebook" />
    
    <!--After user logs in using facebook credentials, make this button visible. Not until.-->
    <input id="btnlauncher" type="button" onclick="LaunchFeedDialog();" value="Launch Feed Dialog"
        class="Hide" />
</body>
</html>

  • After login, just navigate to the "Apps" menu and select "Create a New App". A pop-up will be shown just like this.


  • Provide a name for your app (In my case, it is Dialo). It can be anything you wish. Leave the namespace field blank. You can select a category which is appropriate for your app. Then, click on the "Create App" button. It will prompt you to complete a Captcha. Complete it. You are almost done. 
  • Your app is now created. Let us configure it to work with our code. Select the Settings menu from the left pane. You will see the below screen.



  • Note down the APP ID. We need it later in our code.
  • Enter the name of  App Domain as "localhost" in case you are running this sample on localhost.
  • Now, click on the "+Add Platform" button to see the below screen. Select "Website". The pop-up would close and you will be back to previous screen with a few additional controls displayed in it.


  • Now, enter the path to the virtual directory of the application you just created in the "Site URL" field. In my case, it was "http://localhost:62735/FBPlayground". (In your case, the port number would differ. Just run your website and copy the same port number). 
Say for example, if the test application you created is available at http://localhost/MyDialogTest, provide the same URL in the Site URL box of the above screen. (In case your app will be hosted on a domain, provide the full URL of the site and virtual directory. This is where users are redirected after they login to your app using their facebook credentials. Just be cautious. This URL is very important and your app only works if you provide a valid URL. In case you are using Visual Studio and running the website using the built-in web server, the port number would vary when compared to the one above. I have provided a sample screenshot below which works for me.

  • Save the changes.
Do not forget to change the APP ID in the code above with the actual APP ID of your Facebook app.

Running It


  • In your Visual Studio, set "FeedAndShare.html" as a start page and run the website. You will see the screen below.

  • Click on the "Login with Facebook" button. You would then see the below screen. (If you don't see the below screen, there are two reasons. The website URL you provided while creating Facebook App is not correct or you have opened the html file directly without a web server.)


  • Login with valid Facebook credentials. You would then see a screen requesting permission.


  • Click on the "Okay" button. Now, you will see another option on the screen to launch Feed dialog. The login button would be hidden.

  • Click on the "Launch Feed Dialog" button. You see see the dialog with all the settings configured. You can just type something and share it on your wall.


Now, Login to facebook and check your wall. You will find the post you just shared. All your friends can see it and share it if they like. 

The code is self explanatory. However, I have added a few comments. Go through them. Let me know if it worked for you and even if it doesn't, I will help you to fix it and make it work for you.

Popular posts from this blog

Image upload using JQuery + Uploadify + ASP.Net Custom Handler

Generating reports with Templater, MS Word & C#

Creating a cool Microsoft Word Report for listing Scientists with Templater and C# Generic List