Panini has written an add-on for Google Documents that will automatically shorten all the hyperlinks (URLs) in the existing document using the bit.ly API. You’ll need to supply your own Bitly API key to be able to track clicks inside your Bitly dashboard.
A similar approach may be used to shorten links with goo.gl though you would need to enable the Google URL shorterner service from the services console.
function onOpen(e) {
DocumentApp.getUi().createAddonMenu().addItem('Shorten Links', 'displayLinks').addToUi();
}
function onInstall(e) {
onOpen(e);
}
function displayLinks() {
var doc = DocumentApp.getActiveDocument();
// Get the body text and find all links using regex
var body = doc.getBody().getText();
var links = body.match(/http[s]*:\/\/.+/g);
var encoded = [];
var shortened = [];
var accessToken = 'ENTER_YOUR_BITLY_TOKEN_HERE';
for (i = 0; i < links.length; i++) {
encoded.push(encodeURIComponent(links[i]));
var getRequest = httpGet(
'https://api-ssl.bitly.com' + '/v3/shorten?access_token=' + accessToken + '&longUrl=' + encoded[i]
);
var jsonData = JSON.parse(getRequest);
shortened.push('http://bit.ly/' + jsonData.data.hash + '\n');
// Replace full links with shortened URLs
DocumentApp.getActiveDocument().getBody().replaceText(links[i], shortened[i]);
}
}
function httpGet(url) {
var http = UrlFetchApp.fetch(url);
return http.getContentText();
}
Here’s another snippet by Dave Johnson that shortens URLs in Google Docs using the goo.gl service. It works for even ftp URLs and the good thing is that it ignores URLs that are already shortened.
function shortenUrl() {
var doc = DocumentApp.getActiveDocument();
var body = doc.getBody();
var text = body.getText();
var pattern = new RegExp(
/(http|ftp|https):\/\/(?!goo.gl)([\w\-_]+(?:(?:\.[\w\-_]+)+))([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/g
);
var matches = text.match(pattern);
if (matches != null) {
for (var x = 0; x < matches.length; x++) {
var match = matches[x];
var url = UrlShortener.Url.insert({
longUrl: match,
});
body.replaceText(match, url.id);
}
}
}