Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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>
@Leop0ld

This comment has been minimized.

Copy link

commented Oct 25, 2016

57: gapi.client.setApiKey('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'); //get your ownn Browser API KEY

Fix ownn to own.

@jdc20181

This comment has been minimized.

Copy link

commented Nov 24, 2016

where do we obtain the key?

@MiracCicek

This comment has been minimized.

Copy link

commented Dec 9, 2016

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

@amdrade

This comment has been minimized.

Copy link

commented Jan 16, 2017

great tutorial, thanks!!
+1

@emalherbi

This comment has been minimized.

Copy link

commented Mar 2, 2017

@el3zahaby

This comment has been minimized.

Copy link

commented Mar 19, 2017

image
:( It did not work with me

@hardipraj

This comment has been minimized.

Copy link

commented Oct 8, 2017

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

@azizramdan

This comment has been minimized.

Copy link

commented Nov 9, 2017

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
You can’t perform that action at this time.