I am trying this code but it gives me a DOM Exception. What I want it to get a true/false "answer" from the function using plain Javascript.
var url = 'http://www.google.com/';
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
UrlExists(url);
FIDDLE
I got this code from this SO answer, but as said I cannot get it working...
If you have ever wanted to check whether a page has returned a 404 for any reason, one of the easiest ways is to use this little helper function UrlExists() with the current url, given by window. location. href. This will return a true if the http status is anything except a 404, otherwise it will return false .
You can use the URLConstructor to check if a string is a valid URL. URLConstructor ( new URL(url) ) returns a newly created URL object defined by the URL parameters. A JavaScript TypeError exception is thrown if the given URL is not valid.
404 error codes are generated when a user attempts to access a webpage that does not exist, has been moved, or has a dead or broken link. The 404 error code is one of the most frequent errors a web user encounters. Servers are required to respond to client requests, such as when a user attempts to visit a webpage.
Cross domain does not give any status code. status code is part of the content which is received from server when server responds with yes or no. In case of cross domain server never respond to request.
the second mistake in the code is you cannot capture the status code directly without any waiting time or success event. return statement in function doesn't wait until server response to ajax request, so you cannot depend on it.
Doesn't detect 404 errors, but can check if the page exists or not with a setTimeout()
hack.
// Based on https://stackoverflow.com/a/18552771
// @author Irvin Dominin <https://stackoverflow.com/u/975520>
function UrlExists(url)
{
var iframe = document.createElement('iframe');
var iframeError; // Store the iframe timeout
iframe.onload = function () {
console.log("Success on " + url);
clearTimeout(iframeError);
}
iframeError = setTimeout(function () {
console.log("Error on " + url)
}, 3000);
iframe.src = url;
document.getElementsByTagName("body")[0].appendChild(iframe);
}
UrlExists('http://www.google.com/');
UrlExists('http://www.goo000gle.com');
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