Aug 13th 2010 × mootools Request.JSONP to decode shortened url hashes
I tend to get annoyed about URL baiting that takes place over social networks – you really don’t know what’s behind a shortened URL until you click it. Or… until you run a URL resolver that can help. In building my Twitter Trend Aggregator, I came to explore this and found an invaluable service through the API of longurl.org that can uncrunch almost any shortened URL to its original.
Here is the extended Class (http://www.jsfiddle.net/dimitar/3Ntnr/)
Request.longURL = new Class({
// decode a long url
Extends: Request.JSONP,
options: {
log: !true,
url: "http://api.longurl.org/v2/expand",
data: {
url: "",
format: "json"
}
},
initialize: function(loc, options) {
this.parent(options);
this.options.data.url = loc;
},
success: function(data, script) {
this.parent(data, script);
}
});
// example usage
var urls = [
"http://bit.ly/b5Ukzp",
"http://tinyurl.com/33wz7sv",
"http://is.gd/e7S7R",
"http://post.ly/r49y",
"http://www.google.com/" // won't do anything to it.
];
var output = document.id("output");
urls.each(function(url) {
new Request.longURL(url, {
onSuccess: function(data) {
new Element("a", {
href: data["long-url"],
text: url + " -> " + data["long-url"]
}).inject(output);
}
}).send();
});
For a better example of this, visit the Twitter Trends Thingie I wrote and mouseover any encoded URL (or press the ‘Unshorten Tiny URLs’ link in the top right bar).
If you want to just deal with the good old bit.ly, then you can go to them direct like so:
// get all links on page that are bit.ly and decode them
document.getElements("a[href^=http://bit.ly]").each(function(el) {
var url = el.get("href");
new Request.JSONP({
url: 'http://api.bit.ly/v3/expand',
data: {
shortUrl: url,
apiKey: 'R_e744c730bdde44a7eacc88cb892074e7', // change
login: 'webtogs2' //change this
},
onComplete: function(response) {
el.set({
href: response.data.expand[0].long_url,
text: response.data.expand[0].long_url
});
}
}).send();
});
Happy social networking



