Search code examples
javascriptfacebook-like

Tracking the facebook like button


I have a Facebook like button on my page, and I'd like to track when it is clicked (and by which user, etc). I have the javascript below running (gives alert "running"), but it doesn't give the alert "You liked the URL...", which is where I will put all of my logic:

$( document ).ready(function() {    
  (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#xfbml=1";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

  window.fbAsyncInit = function() {
    alert("running")
    FB.Event.subscribe('edge.create',
      function(response) {
        alert('You liked the URL: ' + response);
      }
    );
  };
});

Does anyone know why this is not firing when the like button is clicked?

EDIT I'm referencing this page when trying to set it up: https://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/

EDIT 2 I'm adding the like button via iframe (the button itself works properly):

<span id="facebook-share-btn">
  <iframe src="//www.facebook.com/plugins/like.php?href=<%= item.short_path %>&amp;send=false&amp;layout=button_count&amp;width=450&amp;show_faces=false&amp;font&amp;colorscheme=light&amp;action=like&amp;height=35" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:48px; height:22px;" allowTransparency="true">
  </iframe>
</span>

Solution

  • It turns out that the callbacks do not work (apparently) with the iframe method. I've switched to the HTML5 method and it works fine.

    Setup:

    <div id='fb-root'></div>
    <script>
      (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#xfbml=1";
        fjs.parentNode.insertBefore(js, fjs);
      }(document, 'script', 'facebook-jssdk'));
    
      FB.init({appId: "myId", status: true, cookie: true});
    
    </script>
    

    Like button:

    <div class="fb-like" 
         data-href="myurl.com" 
         data-send="false" 
         data-layout="button_count" 
         data-width="450" 
         data-show-faces="false">
    </div>