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
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

  • By
    CSS Gradients

    With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements.  CSS gradients are another step in that direction.  Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...

Incredible Demos

  • By
    MooTools-Like Element Creation in jQuery

    I really dislike jQuery's element creation syntax. It's basically the same as typing out HTML but within a JavaScript string...ugly! Luckily Basil Goldman has created a jQuery plugin that allows you to create elements using MooTools-like syntax. Standard jQuery Element Creation Looks exactly like writing out...

  • By
    Skype-Style Buttons Using MooTools

    A few weeks back, jQuery expert Janko Jovanovic dropped a sweet tutorial showing you how to create a Skype-like button using jQuery. I was impressed by Janko's article so I decided to port the effect to MooTools. The XHTML This is the exact code provided by...

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!