Getting visitors to Facebook like your page before showing your page content

Hi Guys,

Well now that I am doing a bit of RnD on Facebook JavaScript API I found out few interesting things. Mind you that this is the first time I am playing with Facebook API so please if my solution is not good enough then don’t forget to leave comments and share yours, so that others can benefit from it.

Lets get back to the point without wasting much time. I noticed few sites, can’t remember which ones though. I think one of them was something to do with coupons, you have to like their page to see a coupon.

The code below will help you with that.

First up is to get our markup set up

The Markup

So the above DIV container is something that Facebook JavaScript library will use to auto generate IFRAME and stuff. That’s their thing so I won’t get into that in depth.

Next up will be converting our above container to a Facebook like button, here is how its done

The JavaScript

Here is the initializer container that you should have a close look at

This code should be placed directly after the opening  tag.

What we are doing above is to embedding FaceBook JS library from URL //connect.facebook.net/en_US/all.js into our webpage header. and we are initializing a newly created property called fbAsyncInit that FaceBook API will be interested in. If you want to have a close view then open the above mentioned URL in your web browsers. A javascript file will be in front of you and then search “fbAsyncInit” on your page to see how it handles it.

Anyway the most inportant part as per my testing goes is FB.init and setting xfbml:true

If we are using the XFBML version of the button, we can subscribe to the ‘edge.create’ event through FB.Event.subscribe.

Lets make that change to our above JavaScript Code

In web world there is a saying that if you can’t demo it then it never happened. So here is

The Demo

 http://jaspreetchahal.org/examples/facebook-like.html

 

Most notable part as stated above is to use fbxml so that we can make use of event subscription. Normal iFrame and HTML5 code doesn’t seem to work with events and stuff.

Resources

https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/

I hope that this post was useful.

As always if you have anything to add, comments are open and stage is all yours

Cheers

Comments

  1. How about test if the user has liked allready?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.