I'm currently checking the status code of the current page with this code :
$.ajax({
type: 'HEAD',
url: window.location.href,
success: function() {
console.log("Ok");
},
error: function() {
console.log("error");
}
});
The page exists if response's code is between 200 - 299 or not if response's codes between 400 - 499.
But for exemple a 405 error is not really an error for me, the page displays well, so no reason to be in the error state.
So I added an another test :
error: function(jqXHR, textStatus, errorThrown) {
console.log('jqHRX : ' + JSON.stringify(jqXHR) + ' textStatus : ' + textStatus + ' errorThrown : ' + errorThrown);
if (errorThrown != "OK") //or jqHRX.statusText
console.log("error");
}
For exemple, if I browse to a page which returns a 405 code, I'll have this output :
jqHRX : {"readyState":4,"responseText":"","status":405,"statusText":"OK"} textStatus : error errorThrown : OK
And if it's a 404 error :
jqHRX : {"readyState":4,"responseText":"","status":404,"statusText":"Not Found"} textStatus : error errorThrown : Not Found
error
Thanks !
Alex
edit : for exemple, https://developer.chrome.com/home returns a 405 with my code but in my application there is no need to consider this like an error.
Strange thing, you can verify the statusCode with http://tools.seobook.com/server-header-checker/ : the result is 405 But if you check with http://httpstatus.io/ the result is 200
tl;dr : Using GET instead of HEAD will work. Get is actually the method not allowed which throwned the 405 error.
Answer : Thanks to a colleague of mine, which shows me Postman.
It allowed me to check the status code of a page via different methods like GET, PUT, POST, HEAD, LOCK, etc. And it appears that for a bunch of websites (chrome developer documentation, Amazon, etc) HEAD returned 405 while GET returned 200
According to w3.org
The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response.
So in my case, sometimes I found website which did not allow HEAD request.
Solved by remplacing the code by :
$.ajax({
type: 'GET',
url: window.location.href,
error: function() {
console.log("error");
}
});