什么是通过JavaScript检查网站是否启动的最佳方式

Te *_*ren 9 javascript

使用JavaScript检查网站是否已启动或运行的最佳方法是什么?

tin*_*tin 8

基于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>
Run Code Online (Sandbox Code Playgroud)

[编辑]

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

时序问题 将xmlhttprequests用于跨源调用时的时序存在差异.由于浏览器必须等待响应以评估可能的访问控制头字段,因此对不存在的网站的调用将在浏览器请求超时中运行.对现有网站的调用不会遇到此超时,并且会出现错误,因为交叉来源异常(仅在浏览器中可见,javascript永远不会显示此信息!).因此,还有可能测量从xmlhttprequest.send()到第一个响应(在回调中)的时间.早期的回调调用将表明网站从浏览器的角度来看,但至少使用xmlhttprequest,您将无法评估返回码(因为这被阻止了bei cross origin策略).

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
Run Code Online (Sandbox Code Playgroud)


Spl*_*ter 7

不需要AJAX,只需从隐藏在站点中的远程站点生成映像,并监视此映像的加载HTTP响应状态.这可能需要对真正的crossbrowser兼容性进行一些调整.

<script type="text/javascript">
function set_test(name,status){
    var el=document.getElementById(name+'_test');
    el.innerHTML=status?'Yes, you are logged in':'No, you\'re not logged in';
    el.style.color=status?'#0a0':'#a00';
    el.style.fontWeight='bold';
}
(function(){
    var gmail_test=document.getElementById('gmail_test');
    gmail_test.innerHTML='Checking...';
    var img=document.createElement('img');
    img.src='//mail.google.com/mail/photos/static/AD34hIhNx1pdsCxEpo6LavSR8dYSmSi0KTM1pGxAjRio47pofmE9RH7bxPwelO8tlvpX3sbYkNfXT7HDAZJM_uf5qU2cvDJzlAWxu7-jaBPbDXAjVL8YGpI?rand='+Math.random();
    img.onload=function(){set_test('gmail',1)};
    img.onerror=function(){set_test('gmail',0)};
    img.style.display='none';
    document.body.appendChild(img);
})();
</script>
Run Code Online (Sandbox Code Playgroud)