Skip to content

Instantly share code, notes, and snippets.

@bamanzi
Created February 20, 2012 03:49
Show Gist options
  • Save bamanzi/1867677 to your computer and use it in GitHub Desktop.
Save bamanzi/1867677 to your computer and use it in GitHub Desktop.
[keysnail] use goo.gl to shorten current URL
ext.add("goo.gl", function () {
let endpoint = "https://www.googleapis.com/urlshortener/v1/url";
let params = { "longUrl": window._content.document.location.href };
let result = util.httpPostJSON(endpoint, params, function (xhr) {
if (xhr.status == 200) {
var ret = JSON.parse(xhr.responseText);
command.setClipboardText(ret.id);
display.echoStatusBar("Short URL copied into clipboard: " + ret.id, 3000);
} else {
display.echoStatusBar("goo.gl service failed: " + xhr.statusText, 3000);
}
});
}, "Shorten URL with http://goo.gl service");
// goo.gl only accepts content-type as 'application/json',
// but keysnail's httpGet/httpPost doesn't support it
util.httpPostJSON= function (url, params, callback) {
let xhr = new XMLHttpRequest();
switch (typeof params)
{
case "string":
// nothing
break;
case "object":
params = JSON.stringify(params)
break;
default:
params = "";
break;
}
let async = typeof callback === "function";
if (async)
{
xhr.onreadystatechange = function () {
if (xhr.readyState === 4)
callback(xhr);
};
}
xhr.open("POST", url, async);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(params);
return xhr;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment