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
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

  • By
    9 More Mind-Blowing WebGL Demos

    With Firefox OS, asm.js, and the push for browser performance improvements, canvas and WebGL technologies are opening a world of possibilities.  I featured 9 Mind-Blowing Canvas Demos and then took it up a level with 9 Mind-Blowing WebGL Demos, but I want to outdo...

Incredible Demos

  • By
    Record Text Selections Using MooTools or jQuery AJAX

    One technique I'm seeing more and more these days (CNNSI.com, for example) is AJAX recording of selected text. It makes sense -- if you detect users selecting the terms over and over again, you can probably assume your visitors are searching that term on Google...

  • By
    MooTools Zebra Table Plugin

    I released my first MooTools class over a year ago. It was a really minimalistic approach to zebra tables and a great first class to write. I took some time to update and improve the class. The XHTML You may have as many tables as...

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!