Reputation: 4544
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)
Upvotes: 79
Views: 35492
Reputation: 2511
Update 2024:
If you need a reliable (currently chrome based only) solution use https://stackoverflow.com/a/76918876/2590616 which is the best choice imho.
Alternatively
Include the status code on the server side, then read it on the client side via JavaScript, e.g.:
a) Java + Thymeleaf + meta tag:
<meta name="statuscode" th:content="${#response.status}">
<script>
const statusCode = document.getElementsByName("statuscode").getAttribute("content");
</script>
b) Java + Thymeleaf + JavaScript variable:
<script th:inline="javascript">
const statusCode = [[${#response.status}]];
</script>
c) PHP + meta tag (unverified):
<meta name="statuscode" content="<?php echo http_response_code() ?>">
<script>
const statusCode = document.getElementsByName("statuscode").getAttribute("content");
</script>
Upvotes: 0
Reputation: 724
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
Upvotes: 10
Reputation: 13544
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
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.
Upvotes: -1