Skip to content

Instantly share code, notes, and snippets.

@hayageek
Last active May 21, 2019 11:57
Show Gist options
  • Save hayageek/4584508 to your computer and use it in GitHub Desktop.
Save hayageek/4584508 to your computer and use it in GitHub Desktop.
Google URL Shortener API Javascript Example
<html>
<head>
</head>
<script type="text/javascript">
function makeShort()
{
var longUrl=document.getElementById("longurl").value;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str ="<b>Long URL:</b>"+longUrl+"<br>";
str +="<b>Short URL:</b> <a href='"+response.id+"'>"+response.id+"</a><br>";
document.getElementById("output").innerHTML = str;
}
else
{
alert("error: creating short url");
}
});
}
function getShortInfo()
{
var shortUrl=document.getElementById("shorturl").value;
var request = gapi.client.urlshortener.url.get({
'shortUrl': shortUrl,
'projection':'FULL'
});
request.execute(function(response)
{
if(response.longUrl!= null)
{
str ="<b>Long URL:</b>"+response.longUrl+"<br>";
str +="<b>Create On:</b>"+response.created+"<br>";
document.getElementById("output").innerHTML = str;
}
else
{
alert("error: unable to get URL information");
}
});
}
function load()
{
gapi.client.setApiKey('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"> </script>
<body>
URL: <input type="text" id="longurl" name="url" value="http://www.hayageek.com" /> <br/>
<input type="button" value="Create Short" onclick="makeShort();" /> <br/> <br/>
URL: <input type="text" id="shorturl" name="url" value="http://www.hayageek.com" /> <br/>
<input type="button" value="Get Short URL Info" onclick="getShortInfo();" />
<div id="output"></div>
</body>
</html>
@jdc20181
Copy link

where do we obtain the key?

@MiracCicek
Copy link

doesn't work for me, (Tried with FF and IE)

@amdrade
Copy link

amdrade commented Jan 16, 2017

great tutorial, thanks!!
+1

@emalherbi-zz
Copy link

@egyjs
Copy link

egyjs commented Mar 19, 2017

image
:( It did not work with me

@hardipraj
Copy link

You are running it locally, try using it live. @el3zahaby

@azizramdan
Copy link

work for me, but didnt show in list https://goo.gl/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment