JavaScript/jQuery check broken links

NawaMan picture NawaMan · Oct 20, 2009 · Viewed 37.8k times · Source

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.

Answer

Justin Johnson picture Justin Johnson · Oct 20, 2009

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);
});