有没有办法从javascript中获取当前网页的http状态?
在网上搜索了一段时间,但完全没有进展...似乎不可能,但想向Stack Overflow咨询是否有什么花哨的解决方法。
(在响应正文中作为其一部分提供它并不可接受,状态应该只能通过http头部获得)
有没有办法从javascript中获取当前网页的http状态?
在网上搜索了一段时间,但完全没有进展...似乎不可能,但想向Stack Overflow咨询是否有什么花哨的解决方法。
(在响应正文中作为其一部分提供它并不可接受,状态应该只能通过http头部获得)
很抱歉,这是完全不可能的。
这在谷歌浏览器中是(实验性的但是)可能的,通过利用来自性能API的responseStatus。我们寻找navigation
entryType,它应该提供页面的HTTP状态。
const navigationData = window.performance.getEntries().find(e => e.entryType === "navigation")
navigationData.responseStatus // 200
替代方案:
const navigationData = window.performance.getEntriesByType('navigation')[0];
navigationData.responseStatus // 200
window.performance.getEntriesByType('navigation')
来替代window.performance.getEntries().find(e => e.entryType === "navigation")
。 - Simon Kissane.find
返回找到的第一个元素,而 getEntriesByType
返回一个数组,所以我们需要查看索引 [0]
。已经更新了答案,提供了另一种选择。干杯! - RepeatQuotations只需使用XMLHttpRequest
请求相同的页面,即URI。假设您的页面在/stop.php
上,在stop.php
中您可以这样做:
<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>
请查看此演示
请您注意,这只是页面的复制,而不是页面本身。我已经在一个页面上使用了这个解决方案,其中服务器可能会在请求来自未经授权的IP地址时生成403禁止状态码,因此这里的条件非常简单,原始页面和您模拟其访问的副本页面之间几乎没有什么区别。
fetch(location.href).then(response => console.log(response.status));
XMLHttpRequest
(如其他答案中所示),并与async: false一起使用,或者使用async/await
,它在底层仍然是异步的,但感觉上是同步的。<meta name="statuscode" th:content="${#response.status}">
<script th:inline="javascript">
const statusCode = [[${#response.status}]];
</script>
PHP + meta标签(未经验证):
<meta name="statuscode" content="<?php echo http_response_code() ?>">
console.log(window.performance.getEntries()[0].responseStatus)
var xhr = new XMLHttpRequest();
xhr.open('GET', window.location.href, false);
xhr.send(null);
console.log(xhr.status);
它不太美观,但你可以使用:
t = jQuery.get(location.href)
.success(function () { console.log(t.status) })
.error(function() { console.log(t.status) });
你只能检查页面加载的状态 尝试:var x = document.readyState; x 的结果可能是以下五个值之一:
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
document.readyState
指的是文档的加载状态,而不是页面的 HTTP 状态。 - csvoss