76

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
  • 30,962
  • 25
  • 85
  • 135
Andrea Zilio
  • 4,444
  • 3
  • 29
  • 34

7 Answers7

58

This is not in any way possible, sorry.

Martin Jespersen
  • 25,743
  • 8
  • 56
  • 68
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
  • 13,303
  • 20
  • 101
  • 195
1

As a one-liner:

fetch(location.href).then(response => console.log(response.status));

This is asynchronous, if you need a synchronous solution use XMLHttpRequest (as in the other answer) together with async: false or use async/await which feels synchronous, but is still asynchronous under the hood.

Attention: There is the potential risk that the status code of this new request isn't the same as the status code of the original page request, for several reasons, like timouts, authentication and so on.

Alternatively

An approach without an extra call would require to include the status code in the page on the server side, then read it on the client side via JavaScript, like so:

Java + Thymeleaf + meta tag:

<meta name="statuscode" th:content="${#response.status}">

Java + Thymeleaf + JavaScript variable:

<script th:inline="javascript">
  const statusCode = [[${#response.status}]];
</script>

PHP + meta tag (unverified):

<meta name="statuscode" content="<?php echo http_response_code() ?>">
RiZKiT
  • 2,107
  • 28
  • 23
1
console.log(window.performance.getEntries()[0].responseStatus)
Riley Bell
  • 407
  • 4
  • 10
  • 1
    Answer needs supporting information Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](https://stackoverflow.com/help/how-to-answer). – moken Jul 23 '23 at 10:13
1

This is (experimental but) possible in chrome by leveraging responseStatus from Performance API. We look for the navigation entryType which should provide the page http status.

const navigationData = window.performance.getEntries().find(e => e.entryType === "navigation")
navigationData.responseStatus // 200

Alternative:

const navigationData = window.performance.getEntriesByType('navigation')[0];
navigationData.responseStatus // 200
RepeatQuotations
  • 635
  • 5
  • 10
  • Note that instead of `window.performance.getEntries().find(e => e.entryType === "navigation")` you can just do `window.performance.getEntriesByType('navigation')` – Simon Kissane Aug 20 '23 at 06:41
  • `.find` returns the first element found, while `getEntriesByType` returns an array, so we'd need to look at index `[0]`. Have updated answer with the alternative. Cheers! – RepeatQuotations Aug 28 '23 at 18:50
-2
var xhr = new XMLHttpRequest();
xhr.open('GET', window.location.href, false);
xhr.send(null);
console.log(xhr.status);
Riley Bell
  • 407
  • 4
  • 10
  • 2
    This answer was reviewed in the [Low Quality Queue](https://stackoverflow.com/help/review-low-quality). Here are some guidelines for [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer). Code only answers are **not considered good answers**, and are likely to be downvoted and/or deleted because they are **less useful** to a community of learners. It's only obvious to you. Explain what it does, and how it's different / **better** than existing answers. [From Review](https://stackoverflow.com/review/low-quality-posts/34564705) – Trenton McKinney Jun 19 '23 at 23:46
  • And it's not really the status of the current page as you're making a new request. – Zsolt Meszaros Jun 20 '23 at 08:57
  • And using XHR is basically already covered in another answer. – General Grievance Jun 28 '23 at 12:38
-4

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) });

That When Eric says, this solution will make a new request from the same paga, and not show status of current request.

  • 8
    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