Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript/jQuery check broken links

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.

like image 990
NawaMan Avatar asked Oct 19 '09 22:10

NawaMan


People also ask

How do you check if a link is broken Javascript?

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.

How do I find broken links in HTML?

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.


2 Answers

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); }); 
like image 74
Justin Johnson Avatar answered Sep 20 '22 15:09

Justin Johnson


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 ...

like image 39
Sebastian Lasse Avatar answered Sep 21 '22 15:09

Sebastian Lasse