Using URL Shortening Services from the Client with Javascript


Recently I needed to build URL shortening into a UI for a client – it’s not rocket science but I thought I’d reproduce the code here for posterity.

There are 2 versions; 1 for Goo.gl and 1 for Bitly.

Browser Compatibility & CORS

This does not work work in IE7/8/9 due to CORS issues.  Both Google and Bitly’s URL shortening APIs are exposed via HTTPS.

The use of an XDomainRequest jQuery plugin will not solve this problem if you’re using the Google shortener, as Google requires that the request Content-Type header is application/json whereas XDomainRequest requires that this be text/plain.

Google

Bitly

Usage

pdogs.urlshortener.shorten(longUrl)
  .done(function(response) {
    console.log(response.shortUrl);
    console.log(response.shortUrlImg);
  })
  .fail(function(response) {
    if (response.error) alert(response.error);
  })
  .always(function() {
  });

Published by

Phil Harding

SharePoint Consultant, Developer, Father, Husband and Climber.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s