Last active
October 3, 2021 12:49
-
-
Save Paanini/c2ac3cb27072712a7ccb to your computer and use it in GitHub Desktop.
Google Apps Script to shorten all URLs in a doc using Bit.ly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function onOpen(e) { | |
DocumentApp.getUi().createAddonMenu() | |
.addItem("Shorten Links", 'displayLinks') | |
.addToUi(); | |
} | |
function onInstall(e) { | |
onOpen(e); | |
} | |
function displayLinks() { | |
var doc = DocumentApp.getActiveDocument(); | |
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") | |
DocumentApp.getActiveDocument().getBody().replaceText(links[i],shortened[i]); | |
} | |
} | |
function httpGet(url) | |
{ | |
var http = UrlFetchApp.fetch(url) | |
return http.getContentText(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Google deprecated their URLShortener API so this came in really handy. Thanks!