71

Is there any way to get the http status of the current web page from javascript?

Spent some time searching on the web, but no luck at all... Seems like it's not possible, but wanted to check with Stack Overflow for maybe some fancy workaround.

(Providing it from the server as part of the response body is not acceptable, the status is supposed to be only available via the http header)

Dharman
  • 26,923
  • 21
  • 73
  • 125
Andrea Zilio
  • 4,344
  • 3
  • 27
  • 34

4 Answers4

53

This is not in any way possible, sorry.

Martin Jespersen
  • 24,934
  • 6
  • 54
  • 66
1
Yes You can

Simply request the same page, i.e. URI, using the XMLHttpRequest. Suppose that your page on /stop.php in stop.php you may do something like:

<script>
function xhrRequest(){            
            console.log(this.status);
            // Do some logic here. 
        }
function getReq(url){
            var oReq = new XMLHttpRequest();
            oReq.addEventListener("load", xhrRequest);
            oReq.open("GET", url);
            oReq.send();
        }
getReq("/stop.php");
</script>

Checkout this DEMO

Note:

You have to note that, it is a copy of the page not the page itself. I, already, have used this solution on a page in which the server may generate Forbidden HTTP status code when the request is come from unauthorized IP address, so the condition here is very simple and there is no much difference between the original and the copy page that you have simulate its visit.

SaidbakR
  • 12,574
  • 18
  • 96
  • 182
-3

It is not beautiful, but you can use:

t = jQuery.get(location.href)
    .success(function () { console.log(t.status) })
    .error(function()    { console.log(t.status) });
Martin Tournoij
  • 24,971
  • 24
  • 101
  • 136
  • 6
    Incorrect: this code makes a new requests, it doesn't get the status of the page as it is currently loaded in the browser. As of 2018, there's no way to get the error status of the currently loaded HTML page for any page. – Eric Nov 06 '18 at 09:03
-5

you can only check status of page loading try:var x = document.readyState; The result of x could be: One of five values:

uninitialized - Has not started loading yet
loading - Is loading
loaded - Has been loaded
interactive - Has loaded enough and the user can interact with it
complete - Fully loaded
  • 6
    `document.readyState` refers to the loading state of the document, not to the page's HTTP status. – csvoss Jun 11 '18 at 22:08