Skip to content

Instantly share code, notes, and snippets.

@jordan-brough
Created November 22, 2017 16:48
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jordan-brough/81518c2a24f89ae771c59e21903b4d87 to your computer and use it in GitHub Desktop.
Save jordan-brough/81518c2a24f89ae771c59e21903b4d87 to your computer and use it in GitHub Desktop.
Goo.gl URL shortener bookmarklet
// Step 1: Get an API key here: https://developers.google.com/url-shortener/v1/getting_started#APIKey
// Step 2: Paste your api key below
// Step 3: Add the code below to your browser as a bookmark
// Step 4: Visit a non-goo.gl URL and click your bookmark
// NOTE: The security policy of some sites (such as this gist.github.com!) will prevent this from working.
// Check your javascript console if something doesn't work.
javascript:(function(){
var googleApiKey = 'INSERT YOUR API KEY HERE';
if (googleApiKey == 'INSERT YOUR API KEY HERE') {
alert('Error: You need to add your api key to this bookmarklet!');
return;
}
var xhr = new XMLHttpRequest();
var url = 'https://www.googleapis.com/urlshortener/v1/url?key=' + googleApiKey;
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
prompt('Your short URL is:', json.id);
} else {
alert('Shortener error: ' + xhr.responseText);
}
}
};
var data = JSON.stringify({'longUrl': window.location.href});
xhr.send(data);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment