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
    5 HTML5 APIs You Didn’t Know Existed

    When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature...

  • By
    6 Things You Didn’t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving...

Incredible Demos

  • By
    MooTools Zoomer Plugin

    I love to look around the MooTools Forge. As someone that creates lots of plugins, I get a lot of joy out of seeing what other developers are creating and possibly even how I could improve them. One great plugin I've found is...

  • By
    Animated AJAX Record Deletion Using jQuery

    I'm a huge fan of WordPress' method of individual article deletion. You click the delete link, the menu item animates red, and the item disappears. Here's how to achieve that functionality with jQuery JavaScript. The PHP - Content & Header The following snippet goes at the...

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!