gpt4 book ai didi

javascript - 通过 JavaScript 检查网站是否正常运行的最佳方法是什么

转载 作者:可可西里 更新时间:2023-11-01 02:54:19 33 4
gpt4 key购买 nike

使用 JavaScript 检查网站是否正常运行或关闭的最佳方法是什么?

最佳答案

基于 Spliffster 的评论:

此代码将基于浏览器超时尝试到达特定 IP,直到它异步可用。您可能想要添加代码以防止它尝试过长。

<head>
<script>
function check_available(ip){
var el=document.getElementById("check_pic");
el.src="https://"+ip+"/images/powered_by.gif?now="+Math.random();
}

function check_success(url){
alert("redirect now :) - url:"+url);
}
</script>
</head>

<body>
<img style="visibility:hidden" id='check_pic' src="/images/powered_by.gif" onabort="alert('interrupted')" onload="check_success('http://10.0.0.1/redirect/me/here')" onerror="check_available('10.17.71.150')"/>

</body>

[编辑]

旁注:xmlhttprequest 将不起作用,因为浏览器会抛出跨源异常。 This mozilla.dev链接提供了更多背景信息并显示了使用访问控制 header 响应语句的示例。请注意,访问控制 header 字段位于服务器端(正在被探测的站点),您可能无法控制该字段(默认情况下未启用)。

时间问题使用 xmlhttprequests 进行跨源调用时,在时间上存在差异。由于浏览器必须等待响应来评估可能的访问控制 header 字段,因此对不存在的网站的调用将遇到浏览器请求超时。对现有网站的调用不会遇到此超时,并会因跨源异常而提前出错(仅在浏览器中可见,javascript 永远不会获取此信息!)。所以也有可能测量从 xmlhttprequest.send() 到第一次响应(在回调中)的时间。一个早期的回调调用将表明该网站从浏览器的 Angular 来看是正常的,但至少使用 xmlhttprequest 你将无法评估返回码(因为这被交叉源策略阻止)。

self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
//stopwatch.stop and calc timediff. timediff < default browser request timeout indicates website is up from this browsers point of view. No clues on request status or anything else, just availability
}
self.xmlHttpReq.send(null);
//stopwatch.start

关于javascript - 通过 JavaScript 检查网站是否正常运行的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4814752/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com