[Twitter] Capturing custom events from tweet button and executing something when clicked

Tadashi Shigeoka ·  Wed, December 2, 2015

I’ll introduce a useful snippet for capturing custom events from Twitter’s tweet button and executing some processing when the tweet button is clicked.

// https://dev.twitter.com/web/javascript/loading より
window.twttr = (function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0],
    t = window.twttr || {};
  if (d.getElementById(id)) return t;
  js = d.createElement(s);
  js.id = id;
  js.src = "https://platform.twitter.com/widgets.js";
  fjs.parentNode.insertBefore(js, fjs);
 
  t._e = [];
  t.ready = function(f) {
    t._e.push(f);
  };
 
  return t;
}(document, "script", "twitter-wjs"));

twttr.ready(function (twttr) {
  twttr.events.bind("tweet", function (event) {
    console.log('Processing you want to call when Tweet button is clicked');
  });
});

A use case example would be measuring tweet button click counts with Google Analytics event tracking functionality.


Reference Information

That’s all from the Gemba.