JavaScript/jQuery check broken links

Viewed 40526

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.

6 Answers

Like Sebastian says it is not possible due to the same origin policy. If the site can be published (temporarily) on a public domain you could use one of the link checker services out there. I am behind checkerr.org

As others have mentioned, because of JavaScript's same origin policy, simply using the function from the accepted answer does not work. A workaround to this is to use a proxy server. You don't have to use your own proxy for this, you can use this service for example: https://cors-escape.herokuapp.com (code here).

The code looks like this:

var proxyUrl = "https://cors-anywhere.herokuapp.com/";

function urlExists(url, callback) {
  var sameOriginURL = proxyUrl + url;
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      callback(xhr.status < 400);
    }
  };
  xhr.open('HEAD', sameOriginURL);
  xhr.send();
}

urlExists(someUrl, function(exists) {
  console.log('"%s" exists?', someUrl, exists);
});
Related