I’m attempting to detect broken links on a web page using JavaScript, and I’ve run into a problem. Is there any way to detect non-existent URLs using client-side JavaScript, as seen below?
function URLExists(theURL){
//return true if the URL actually exists, and return false if it does not exist
}
//test different URLs to see if they exist
alert(URLExists("https://www.google.com/")); //should print the message "true";
alert(URLExists("http://www.i-made-this-url-up-and-it-doesnt-exist.com/")); //should print the message "false";
Due to Same Origin Policy, you would need to create a proxy on a server to access the site and send back its availability status – for example using curl:
Now you can ajax to that script with the URL you want to test and read the status returned, either as a JSON or JSONP call
The best client-only workaround I have found, is to load a site’s logo or favicon and use onerror/onload but that does not tell us if a specific page is missing, only if the site is down or have removed their favicon/logo: