Javascript module for shortening URLs using Google (goo.gl)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($,window) { | |
"use strict"; | |
window.pdogs = window.pdogs || {}; | |
pdogs.urlshortener = function() { | |
var | |
_googlAPIKey = '<YOUR GOOGLE APIKey HERE>', | |
_module = { shorten: shorten }; | |
return _module; | |
function shorten(longUrl, sync) { | |
var p = $.Deferred(); | |
if (typeof longUrl === 'undefined' || !longUrl || !longUrl.length) { | |
p.reject({ error: 'Invalid/Empty URI' }); | |
return p.promise(); | |
} | |
var | |
decodedLongUrl = decodeURIComponent(longUrl), | |
params = 'key='+_googlAPIKey, | |
r = { | |
type: 'POST', | |
url: 'https://www.googleapis.com/urlshortener/v1/url?' + params, | |
headers: { | |
'Accept': 'application/json', | |
'Content-Type': 'application/json' | |
}, | |
data: "{ longUrl: '" + decodedLongUrl + "' }", | |
async: !sync | |
}; | |
jQuery.support.cors = true; | |
$.ajax(r) | |
.done(function(response) { | |
if (response.error) p.reject({ error: '[' + response.error.code+'] ' + response.error.message }); | |
else | |
p.resolve({ shortUrl: response.id, shortUrlImg: response.id + '.qr', longUrl: response.longUrl }); | |
}) | |
.fail(function(xhr,textStatus, error) { | |
var m = error.message ? error.message : error; | |
p.reject({ error: 'goo.gl] ' + textStatus + ': ' + m }); | |
}); | |
return p.promise(); | |
} | |
}(); | |
})(jQuery,window); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment