I want to check, if a website is reachable with XMLHttpRequest.
I wrote a JS-function: UrlExsists(url)
; to try and establish a connection.
function UrlExists(url) {
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
if (http.status != 404) {
console.log("did work:" + url)
} else {
console.log("did not work:" + url)
}
};
When i go to my browser console and call the function like so:UrlExsists("https://www.google.com/");
, the following is displayed in the console:
"XHR HEAD https://www.google.com/ [HTTP/2.0 200 OK 668ms]"
But It fails due to "Cross-Origin Request Blocked" and a Network Error occurs. = >img as reference
If I call UrlExsists("https://www.google.com/test");
the following is displayed:
"XHR HEAD https://www.google.com/test [HTTP/2.0 404 Not Found 0ms]"
And again "Cross-Origin Request Blocked" and Network Error. = > img as reference
Now these Status codes 404 and 200 are exactly, what i want, but how do i get these in javascript, to determine if the given website is available?
And if I'm on the wrong track, can someone maybe nod me to the right one?