Created
January 28, 2023 00:37
-
-
Save JayGoldberg/5cc623577ca328af1c053f70782e0aea to your computer and use it in GitHub Desktop.
Google Sheets function to recursively resolve URLs and get status codes =getStatusCode() and =getRedirects()
This file contains hidden or 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
const options = { | |
'muteHttpExceptions': true, | |
'followRedirects': false | |
}; | |
function getStatusCode(url) { | |
const url_trimmed = url.trim(); | |
let cache = CacheService.getScriptCache(); | |
let result = cache.get(url_trimmed); | |
if (!result) { | |
const response = UrlFetchApp.fetch(url_trimmed, options); | |
const responseCode = response.getResponseCode(); | |
cache.put(url_trimmed, responseCode, 21600); | |
result = responseCode; | |
} | |
return result; | |
} | |
function getRedirects(url) { | |
const response = UrlFetchApp.fetch(url, options); | |
const redirectURL = response.getHeaders()['Location']; | |
// resolve recursively | |
if (response.getResponseCode() == 301) { | |
return getRedirects(redirectURL) | |
} | |
return redirectURL; | |
} | |
// adapted from https://blog.webverge.io/check-http-status-code-and-redirected-urls-on-google-sheets/#How_to_Check_HTTP_status_codes_and_Redirected_URLs_on_Google_Sheets |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment