Endpoint Resolver

The Endpoint Resolver is a simple library that takes a URL and returns the final destination of that URL. It tries to follow a Location: header.

How it works

Given the URL, it gets passes to a server side resolver that hits the URL to get the headers. If a Location: header appears it is a redirect (ignoring 301, 302 for now, so a 200 + Location would count).

Since this happens via JSONP, it happens asynchronously via appending the script to the DOM. This is why you pass in a callback that will be passed the new URL, and the original one.

If the URL has been changed they will of course be different, and a simple helper Endpoint.isRedirecting(url, orig) will do that test for you.

Why?

The reason I built this was for a Twitter client. Seeing tinyurl / snurl / is.gd / twurl / .... URLs is ugly, and it can be scary not knowing where you are going, so wouldn't it be nice to convert them back to the real URL?

I built a Twitter Resolve URL Greasemonkey script to do just that.

Examples

    // Simplest version
    Endpoint.resolve('http://snurl.com/2luj3', function(url) { 
      alert(url); 
    });
    
    // Used in the form below
    Endpoint.resolve(
      document.getElementById('testurl').value, 
      function(url) { alert(url); }
    );
    
    // Using the original URL to work out if it has changed
    Endpoint.resolve(
      document.getElementById('testurl').value, 
      function(url, orig) { 
        alert(url); 
        alert(Endpoint.isRedirecting(url, orig));
      }
    );
    
    // How it is used in the Twitter Endpoint Resolver
    Endpoint.resolve(url, function(resulturl, originalurl) {
      if (!Endpoint.isRedirecting(resulturl, originalurl)) return;
      
      newtext = newtext.replace(originalurl, resulturl, "g");
      jQuery(el).html(newtext);
    });
  

Endpoint Resolver Demo

The Code

All of the code (JavaScript / PHP) is available thanks to Google Code. I wanted to host this service on App Engine, but couldn't find a way to get the correct headers from the fetch() as it seems to automatically follow the redirects so you end up with the final page.