I am grabbing all the url links from an HTML page and calling a function to send an XHR request for all the url links. I would like to console log for those passed and failed requests links in a proper way. I have got my result to some extent but not happy the way of console logs/errors. Can someone please advise where I need to correct console log ?
<div id="WebLinks">
<h2>All Links</h2>
<a href="https://jsfiddle.net/">Link 1</a><br>
<a href="https://stackoverflow.com/">Link 2</a><br>
<a href="https://tellus.com">Link 3</a><br>
<a href="https://loudop.com">Link 4</a><br>
<a href="https://www.youtube.com">Link 5</a><br><br>
<input type="button" id="linkChecker" onclick="linkCheck();" value="linkChecker">
</div>
// How can I improve the console logs for passed and failed ones. Also remove some of console errors;
var linkCheck = function() {
var arr = [],
l = document.links;
for (var i = 0; i < l.length; i++) {
arr.push(l[i].href);
console.log(arr[i]);
urlCheck(arr[i]);
}
function urlCheck(arr, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (callback) {
callback(xhr.status < 400);
}
}
};
xhr.open('HEAD', arr);
xhr.send();
}
urlCheck(arr, function(exists) {
console.log('"%s" exists?', arr, exists);
});
}
You can do that with fetch
API using mode: "no-cors"
option:
window.linkCheck = function() {
function urlCheck(link) {
fetch(link, {mode: "no-cors"}).then(
() => console.log(`${link} is valid`),
() => console.log(`${link} is invalid`)
);
}
var arr = [],
l = document.links;
for (var i = 0; i < l.length; i++) {
arr.push(l[i].href);
urlCheck(arr[i]);
}
};
<div id="WebLinks">
<h2>All Links</h2>
<a href="https://jsfiddle.net/">Link 1</a><br>
<a href="https://stackoverflow.com/">Link 2</a><br>
<a href="https://tellus.com">Link 3</a><br>
<a href="https://loudop.com">Link 4</a><br>
<a href="https://www.youtube.com">Link 5</a><br><br>
<input type="button" id="linkChecker" onclick="linkCheck();" value="linkChecker">
</div>