通过 JavaScript 检查网站是否启动的最佳方法是什么
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4814752/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the best way to check if a website is up or not via JavaScript
提问by Te Riu Warren
What is the best way to check if a site is up and running or down with JavaScript?
使用 JavaScript 检查网站是否正常运行或关闭的最佳方法是什么?
采纳答案by tintin
Based on Spliffster's comment:
根据 Spliffster 的评论:
This code will based on the browser timeout try to reach a specific IP until it is available asynchronously. You may want to add code to prevent it from trying to long.
此代码将基于浏览器超时尝试到达特定 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>
[Edit]
[编辑]
Sidenote: xmlhttprequest will not work as the browser will throw a cross origin exception. This mozilla.devlink gives more background infos and shows examples using access control header response statements. Be aware that the access control header field is serverside (the site that is being probed) and you might not be able to control that field (not enabled by default).
旁注: xmlhttprequest 将不起作用,因为浏览器会抛出跨源异常。这个 mozilla.dev链接提供了更多背景信息并显示了使用访问控制头响应语句的示例。请注意,访问控制标头字段是服务器端(正在被探测的站点),您可能无法控制该字段(默认情况下未启用)。
timing issuesThere are differences in timing when using xmlhttprequests for cross origin calls. Since the browser must wait for the response to evaluate possible access control header fields, a call to a non existent website will run into the browsers request timeout. A call to an existing website will not run into this timeout and error out earlier with a cross origin exception (only visible in the browser, javascript never gehts this info!). So there's also the possibility to measure the time from xmlhttprequest.send() to first response (in callback). An early callback call will indicate that the website is up from the browsers point of view but at least with xmlhttprequest you wont be able to evaluate the returncode (since this is blocked bei cross origin policy).
计时问题使用 xmlhttprequests 进行跨源调用时,计时存在差异。由于浏览器必须等待响应以评估可能的访问控制标头字段,因此对不存在的网站的调用将遇到浏览器请求超时。对现有网站的调用不会遇到此超时,并且会因跨源异常而提前出错(仅在浏览器中可见,javascript 永远不会获取此信息!)。所以也有可能测量从 xmlhttprequest.send() 到第一次响应(在回调中)的时间。早期的回调调用将表明从浏览器的角度来看该网站已启动,但至少对于 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
回答by Spliffster
No AJAX required, just plant an image from the remote site hidden into your site and monitor the load HTTP response status of this image. This might need some tweaks for true crossbrowser compatibility.
不需要 AJAX,只需将远程站点的图像隐藏到您的站点中,并监控该图像的负载 HTTP 响应状态。这可能需要对真正的跨浏览器兼容性进行一些调整。
<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>
回答by Or Weinberger
Make a get ajax call and examine the output.
进行 get ajax 调用并检查输出。
Or, make a get ajax call to isitup.org and examine the output
或者,对 isitup.org 进行 get ajax 调用并检查输出
回答by Fenton
That's quite difficult to do with JavaScript as you will encounter cross-site scripting problems.
JavaScript 很难做到这一点,因为您会遇到跨站点脚本问题。
It is much easier to do with a server-side language as you can attempt to load any web page.
使用服务器端语言要容易得多,因为您可以尝试加载任何网页。
At the very least, you will most likely need to implement a server-side proxy to get the remote page for you. There are lots of examples for this - let me know what language you can use server side and I can find you an example.
至少,您很可能需要实现服务器端代理来为您获取远程页面。有很多示例 - 让我知道您可以使用服务器端的语言,我可以为您找到一个示例。
回答by cstruter
Ajax alone might not be the answer - if you're trying to check a remote server, since by default you can't access a remote server via ajax.
Ajax 本身可能不是答案 - 如果您尝试检查远程服务器,因为默认情况下您无法通过 ajax 访问远程服务器。
You can however access the server that the script resides/lives on - which means you can create some kind of script that acts as a proxy e.g. server side script that checks if the site in question is active and call that script via your ajax call.
但是,您可以访问脚本驻留/所在的服务器 - 这意味着您可以创建某种充当代理的脚本,例如服务器端脚本,用于检查相关站点是否处于活动状态并通过您的 ajax 调用调用该脚本。
An example (PHP/C# & VB.Net) of how to do this: http://www.cstruter.com/articles/article/2/8
如何执行此操作的示例(PHP/C# 和 VB.Net):http: //www.cstruter.com/articles/article/2/8
As for Checking the status of the server:
至于检查服务器的状态:
C#
C#
string URL = "http://www.stackoverflow.com";
WebRequest request = WebRequest.Create(URL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//if (response.StatusCode == HttpStatusCode.something
PHP
PHP
@$headers = get_headers($url);
return (preg_match('/^HTTP\/\d.\d\s+(200|301|302)/', $headers[0]));
@$headers = get_headers($url);
return (preg_match('/^HTTP\/\d.\d\s+(200|301|302)/', $headers[0]));