Skip to content

Instantly share code, notes, and snippets.

@davchana
Forked from danixland/googl.html
Created October 3, 2017 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davchana/ab936190f7339bb35d93a064db1fe57a to your computer and use it in GitHub Desktop.
Save davchana/ab936190f7339bb35d93a064db1fe57a to your computer and use it in GitHub Desktop.
goo.gl bookmarklet - this bookmarklet will return the shortened url of the current page
<a href="javascript:var%20uri=window.location.href;xhr=new%20XMLHttpRequest();xhr.open('POST','https://www.googleapis.com/urlshortener/v1/url',false);xhr.setRequestHeader('Content-Type','application/json');xhr.send(JSON.stringify({longUrl:uri}));var%20json=xhr.responseText;var%20obj=JSON.parse(json);alert(obj.id);">goo.gl this page</a>
@davchana
Copy link
Author

davchana commented Oct 3, 2017

Working Code as of Now

var url = window.location.href;
xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.googleapis.com/urlshortener/v1/url?key=XXXXXXXXXXXXXXX', false);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    longUrl: url
}));
var json = xhr.responseText;
var obj = JSON.parse(json);
prompt('short url', obj.id);

Get Key from https://developers.google.com/url-shortener/v1/getting_started#APIKey (&replace XXXXXXXX with it)

Minified above code: (replace XXXX with your key):

var a=window.location.href;xhr=new XMLHttpRequest;xhr.open("POST","https://www.googleapis.com/urlshortener/v1/url?key=XXXXXX",!1);xhr.setRequestHeader("Content-Type","application/json");xhr.send(JSON.stringify({a:a}));var b=JSON.parse(xhr.responseText);prompt("short url",b.id);

Bookmarkified above code: (replace XXXX with your key):

javascript:function()%7Bvar%20a%3Dwindow.location.href%3Bxhr%3Dnew%20XMLHttpRequest%3Bxhr.open(%22POST%22%2C%22https%3A%2F%2Fwww.googleapis.com%2Furlshortener%2Fv1%2Furl%3Fkey%3DXXXXXX%22%2C!1)%3Bxhr.setRequestHeader(%22Content-Type%22%2C%22application%2Fjson%22)%3Bxhr.send(JSON.stringify(%7Ba%3Aa%7D))%3Bvar%20b%3DJSON.parse(xhr.responseText)%3Bprompt(%22short%20url%22%2Cb.id)%7D)()

above code will not work without Valid key (Error: Bad Key)

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