简体   繁体   English

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

[英]What's the best way to check if a website is up or not via JavaScript

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

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.此代码将基于浏览器超时尝试到达特定 IP,直到它异步可用。 You may want to add code to prevent it from trying to long.您可能想要添加代码以防止它试图变长。

<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.旁注: xmlhttprequest 将不起作用,因为浏览器会抛出跨源异常。This mozilla.dev link gives more background infos and shows examples using access control header response statements.这个 mozilla.dev链接提供了更多背景信息,并显示了使用访问控制标头响应语句的示例。 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).请注意,访问控制标头字段是服务器端(正在被探测的站点),您可能无法控制该字段(默认情况下未启用)。

timing issues There are differences in timing when using xmlhttprequests for cross origin calls.计时问题使用 xmlhttprequests 进行跨源调用时,计时存在差异。 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!).对现有网站的调用不会遇到此超时,并且会因跨源异常而提前出错(仅在浏览器中可见,javascript 永远不会获取此信息!)。 So there's also the possibility to measure the time from xmlhttprequest.send() to first response (in callback).所以也有可能测量从 xmlhttprequest.send() 到第一次响应(在回调中)的时间。 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).早期的回调调用将表明从浏览器的角度来看该网站已启动,但至少使用 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

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.不需要 AJAX,只需将远程站点的图像隐藏到您的站点中,并监控该图像的负载 HTTP 响应状态。 This might need some tweaks for true crossbrowser compatibility.这可能需要对真正的跨浏览器兼容性进行一些调整。

<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>

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 调用并检查输出

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.有很多示例 - 让我知道您可以使用服务器端的语言,我可以为您找到一个示例。

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 eg 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])); return (preg_match('/^HTTP\\/\\d.\\d\\s+(200|301|302)/', $headers[0]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 通过Javascript检查加载控制状态的最佳方法是什么 - What is the best way to check control state on load via Javascript 通过JavaScript进行网站图像管理 - 处理这个问题的好方法是什么? - Website image management via JavaScript - what's a good way to handle this? 通过javascript修改网址的最佳方法是什么? - What's the best way to amend a url via javascript? 在JavaScript中检查&gt; =和&lt;=的最佳方法是什么? - What is the best way to check >= and <= in Javascript? 在Javascript中检查对象是否为数组的最佳方法是什么? - What is the best way to check if an object is an array or not in Javascript? 在 javascript 中检查变量类型的最佳方法是什么 - what is the best way to check variable type in javascript 检查哈希是否存在的最佳方法是什么? - What's the best way to check for the presence of a hash? 网站检查用户是否安装了客户端应用程序的最佳方式是什么? - What is the best way for a website to check if a user has installed a client app? 在Rails应用程序中拆分Javascript或Coffeescript的最佳方法是什么? - What's the best way to split up my Javascript or Coffeescript in a Rails app? 调试Javascript / AngularJS的最佳方法是什么? - What's the best way to debug Javascript/AngularJS?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM