I developed a small Javascript/jQuery program to access a collection of pdf files for internal use. And I wanted to have the information div of a pdf file highlighted if the file actually exist.
Is there a way to programmatically determine if a link to a file is broken? If so, How?
Any guide or suggestion is appropriated.
Simple link checker using XMLHttpRequest forEach(function(link){ var http = new XMLHttpRequest(); var reportLine = {url: link. getAttribute('href'), status:0, message : "", element : link}; http. open('HEAD', reportLine. url); linkReport.
Use your web browser to visit the W3C Link Checker. In the Enter the address (URL) of a document that you would like to check text box, type the URL of the site you want to scan. To see only the relevant output, select the Summary Only check box.
If the files are on the same domain, then you can use AJAX to test for their existence as Alex Sexton said; however, you should not use the GET
method, just HEAD
and then check the HTTP status for the expect value (200, or just less than 400).
Here's a simple method provided from a related question:
function urlExists(url, callback) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { callback(xhr.status < 400); } }; xhr.open('HEAD', url); xhr.send(); } urlExists(someUrl, function(exists) { console.log('"%s" exists?', someUrl, exists); });
Issue is that JavaScript has the same origin policy so you can not grab content from another domain. This won't change by upvoting it (wondering about the 17 votes). I think you need it for external links, so it is impossible just with .js ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With