Retrieve Twitter and Facebook Counts with JSONP

Datetime:2016-08-22 23:51:30          Topic: JSONP  JavaScript           Share

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:

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

function getTwitterCount(url) {
	var script = document.createElement('script');
	script.async = true;
	script.src = 'http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=twitterCallback';
	document.body.appendChild(script);
}

// Usage:  getTwitterCount('http://davidwalsh.name/twitter-facebook-jsonp');


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

function getFacebookCount(url) {
	var script = document.createElement('script');
	script.async = true;
	script.src = 'https://graph.facebook.com/?id=' + url + '&callback=facebookCallback';
	document.body.appendChild(script);
}

// Usage:  getFacebookCount('http://davidwalsh.name/twitter-facebook-jsonp');

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.





About List