Retrieve Twitter and Facebook Counts with JSONP

By  on  

I've been annoyed that many popular APIs have moved to require authentication in order to retrieve information.  If I can browse a page and get said information, why can't I simply pull it with some simple code and skip the authentication bit?  I had thought that both Twitter and Facebook required authentication to retrieve basic post counts, but it turns out you can grab those with JSONP.  Here's how you do it.

The JavaScript

I'm going to use basic JavaScript to show you how to do this:

// Tiny object for getting counts
var socialGetter = (function() {
	/* just a utility to do the script injection */
	function injectScript(url) {
		var script = document.createElement('script');
		script.async = true;
		script.src = url;
		document.body.appendChild(script);
	}

	return {
		getFacebookCount: function(url, callbackName) {
			injectScript('https://graph.facebook.com/?id=' + url + '&callback=' + callbackName);
		},
		getTwitterCount: function(url, callbackName) {
			injectScript('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=' + callbackName);
		}
	};
})();

// Callbacks to do something with the result
function twitterCallback(result) {
	result.count && console.log('The count is: ', result.count);
}

function facebookCallback(result) {
	result.shares && console.log('The count is: ', result.shares);
}

// Usage
socialGetter.getFacebookCount('https://davidwalsh.name/twitter-facebook-jsonp', 'facebookCallback');
socialGetter.getTwitterCount('https://davidwalsh.name/twitter-facebook-jsonp', 'twitterCallback');

There are hundreds of all-encompassing to tiny micro-frameworks that manage JSONP so the most important part of this post is likely the URLs to  retrieve counts from. Use whatever tool you think is best!

Twitter and Facebook surely limit the rate at which you can make these requests, so it's very possible that JSONP is just the wrong route to go if you run a popular site.  One quick solution is to store the count values in sessionStorage, but that's only a per-user basis.  If you run a site that gets decent traffic, your best bet if probably grabbing the count on the server side and caching it for a given period of time.

Recent Features

  • By
    Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

  • By
    5 More HTML5 APIs You Didn’t Know Existed

    The HTML5 revolution has provided us some awesome JavaScript and HTML APIs.  Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers.  Regardless of API strength or purpose, anything to help us better do our job is a...

Incredible Demos

  • By
    Smooth Scrolling with MooTools Fx.SmoothScroll

    I get quite a few support requests for my previous MooTools SmoothScroll article and the issue usually boils down to the fact that SmoothScroll has become Fx.SmoothScroll. Here's a simple usage of Fx.SmoothScroll. The HTML The only HTML requirement for Fx.SmoothScroll is that all named...

  • By
    HTML5 Context Menus

    One of the hidden gems within the HTML5 spec is context menus. The HTML5 context menu spec allows developers to create custom context menus for given blocks within simple menu and menuitem elements. The menu information lives right within the page so...

Discussion

  1. Ironically enough, I was doing the same thing at work a couple of days ago.

    Until I found this post from Twitter Devs forums (https://dev.twitter.com/discussions/5653) which basically says you are not allowed to make Ajax requests to `http://urls.api.twitter.com/1/urls/count.json?`. You should either use the official Twitter buttons or the Twitter API (which API key and all the stuff…).

  2. I had thought the same thing but this seemingly still works, so people may be able to ride it out. If results stop being returned, people can lazy load the bloated social widgets.

  3. Thanks for the article! I just wrote a bookmarklet which will tell you how many shares a link has had on Facebook and Twitter when you hover over it, and I used stuff from this article:

    https://github.com/callumacrae/socialSharesBookmarklet

  4. Greate tutorial, i always have to create app, use sdk and have to authorize to get these informations.

    Be a little higher, you know how to get fans from facebook? for example, if there is a page with 1000 fans and i wanna get uid of that 1000 fans. Actually, i just can get 500 latest fan.

    Thanks and best regards,

  5. Hi,
    Nice! I’ve done the same thing using node.js to monitor social endorsement from many different sources :

    YCombinator aka Hackers News
    Facebook likes
    Google+
    Twitter
    LinkedIn
    Dzone
    Digg
    Delicious.

    http://www.nodejs-news.com/fun-with-nodejs/monitor-social-endorsement/

    Best regards,
    Vincent

  6. Possibly not the way you were trying to achieve it but sharedcount.com has an API for JSON / JSON-P which also covers other social networks as well such as Digg, Delicious, LinkedIn and Pinterest.
    http://www.sharedcount.com/

  7. MarkL

    This method does not return the correct count from Twitter.

  8. The Twitter JSONP endpoint you’re using is the same endpoint used by their widgets, so I don’t think they could tell the difference between using it in a widget and just directly hitting it through your own code.

  9. Hi there, i get

    Uncaught ReferenceError: twitterCallback is not defined count.json?
    Uncaught ReferenceError: facebookCallback is not defined 
    

    http://jsfiddle.net/wVqG6/

    Any idea?

    thanks

    • Because your functions are defined as stand-alone, not as part of socialGetter.

  10. “If I can browse a page and get said information, why can’t I simply pull it with some simple code and skip the authentication bit?”
    Because of money, dollars, dough, paycheck, mula, cash, bank. :)

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!