Last active
February 9, 2022 16:02
-
-
Save HollowMan6/cf934dededa1942213bff53131ca0bb3 to your computer and use it in GitHub Desktop.
JS script for checking broken links (also include unavailable anchors on the same page)
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
// Script for checking broken links (also include unavailable anchors on the same page) | |
// Note: | |
// Due to cross-domain issues, we can't count the numbers of the errors for cross-domain URL. | |
// So we can only count the broken links that are in the same domain. | |
// For those cross-domain links, please check the error messages in the console. | |
async function doCheck() { | |
// The HTML block id to find links | |
var id = 'content'; | |
var ele = document.getElementById(id).getElementsByTagName('a'); | |
var x = 0; | |
var error_links = {}; | |
for (var i = 0; i < ele.length; i++) { | |
var href = ele[i].getAttribute('href'); | |
if (href) { | |
await fetch(href, { | |
method: 'HEAD', | |
mode: 'no-cors', | |
}).then((response) => { | |
// For cross-domain links, we can't check the status code, so we have to pass them. | |
// However, we can check the error messages in the console if there're issues. | |
if (response.ok || response.type == 'opaque') { | |
ele[i].style.border = '2px dotted green'; | |
// Check anchors on the same page. | |
if (href.startsWith('#')) { | |
if (document.querySelectorAll(href).length !== 1) { | |
x++; | |
error_links[href] = "There're " + document.querySelectorAll(href).length + " elements matching"; | |
ele[i].style.border = '2px dotted red'; | |
} | |
} | |
} else { | |
x++; | |
error_links[href] = response.status + ": " + response.statusText; | |
ele[i].style.border = '2px dotted red'; | |
} | |
}).catch((error) => { | |
x++; | |
error_links[href] = error.message; | |
ele[i].style.border = '2px dotted red'; | |
}); | |
} | |
} | |
console.log(error_links); | |
console.log("Done, " + x + " broken links found."); | |
return error_links; | |
} | |
doCheck(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment