Wednesday, October 16, 2013

[Facebook] Tracking social plugin like button callback

>
system start up....
↑ Here is the Status Bar ↑

If you using Facebook Social Plugin , you can like and comment on each page , but you can't calculate how many like, comment, unlike, comment-delete happed on the webpage if you only using Social Plugin , so we need to add something to tracking those events.

如果你有再用Facebook Social Plugin , 你可以在每個頁面上按讚、留言,但是只用Socail Plugin並沒辦法計算有多少讚、留言產生或是取消,所以我們需要加點東西來追蹤這些事件。

Facebook Javascript SDK has a feature called FB.Event.subscribe https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/ , it can "Attaches an handler to an event and invokes your callback when the event fires." , then we can get that we need.

Facebook Javascript SDK 有個功能叫做 FB.Event.subscribe ,它可以在事件上掛上handler,然後在事件觸發時 callback ,然後我們就可以取得我們要想的東西了。


The main code is like that
主要的語法是這樣
    //like
    FB.Event.subscribe('edge.create', function(href, widget) {
        alert('You liked the URL: ' + href);
    });
    //unlike
    FB.Event.subscribe('edge.remove', function (href, widget) {
        alert('You unliked the URL: ' + href);
    });

If you put it on webpage , remember do FB.init first, Complete Code like this
如果要放到頁面的話,記得先FB.init,完整的Code像這樣
<div id="fb-root"></div>
<script>
  window.fbAsyncInit = function() {
    // init the FB JS SDK
    FB.init({
      appId      : 'YOUR_APP_ID',                        // App ID from the app dashboard
      channelUrl : '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel file for x-domain comms
      status     : true,                                 // Check Facebook Login status
      xfbml      : true                                  // Look for social plugins on the page
    });
    FB.Event.subscribe('edge.create', function(href, widget) {
        alert('You liked the URL: ' + href);
    });
    FB.Event.subscribe('edge.remove', function (href, widget) {
        alert('You unliked the URL: ' + href);
    });
    // Additional initialization code such as adding Event Listeners goes here
  };

  // Load the SDK asynchronously
  (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/all.js";
     fjs.parentNode.insertBefore(js, fjs);
   }(document, 'script', 'facebook-jssdk'));
</script>

下面這是測試的Like按扭。 This is a Test like button.

>
system start up....
↑ Here is the Status Bar ↑

No comments:

Post a Comment