Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Javascript module for shortening URLs using Google (goo.gl)
(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
You can’t perform that action at this time.