How to check if site is online with JavaScript? Plus tips on how to make the rest of this function work better

我的未来我决定 提交于 2021-02-19 08:21:13

问题


I need to check if a website is online and to get ping time.

I already have a rough ping time (close enough). But I still need to check if the site is online and make the function run five times, and get the lowest ping value (in order to get it more accurate).

My code so far:

<script>
  function initPingTest(siteUrl){
    pingTester();
    function pingTester(){
      document.getElementById('site').innerHTML = '<center>' + siteUrl + '</center>';
      document.getElementById('pingT').innerHTML = '<center> testing.. </center>';
    var startTime=new Date();
    window.startTime=startTime.getTime();
    var imgSrc=siteUrl+ '?cacheBuster='+Math.random();
    var iFrame=document.getElementById('myPingTest');
    iFrame.onload=pingTime;
    iFrame.src=imgSrc;
    function pingTime() {
      var endTime=new Date();
      var pingResult = (endTime.getTime()-window.startTime);
      if(pingResult<hidden.hidden.value){
        document.getElementById('pingT').innerHTML = '<center>' + pingResult + '</center>';
        hidden.hidden.value=pingResult;
      }else{document.getElementById('pingT').innerHTML = '<center>' + hidden.hidden.value + '</center>';}
      } 
    } 
  }
</script>

<IFRAME style="display:none;" id=myPingTest></IFRAME>
<FORM NAME="hidden" STYLE="display:none"><INPUT TYPE="text" NAME="hidden" value="100000"></form>
<br>
<FORM method="get" NAME="ping" action="javascript:initPingTest(ping.url.value);"><font>Enter site adress(ie.www.yahoo.com)<br>http://</font>
  <INPUT TYPE="text" NAME="url" size="18"><input type="submit" value="Ping"/></form>
  <br>
  <table cellspacing=5px>
    <tr><th>
      Url:
    </th><th>
      Ping Time (miliseconds)
    </th></tr>
    <tr><td>
      <label id=site><center> - </center></label>
    </td><td>
      <label id=pingT><center> - </center></lable>
    </td></tr>
  </table>
</body></html>

回答1:


While I don't believe Javascript 'really' offers this kind of functionality, you could create an xmlhttprequest object, and perhaps compare the difference from the time it sends with the time it connects.

The following code shows a possible way to achieve this: Edit: should alert if the server is down now

var address = "http://www.google.com";

var t1 = Date.now();
var t2;

var max = 100000;
var failed = false;

var httpReq = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
if(httpReq == null) {
    console.log("Error: XMLHttpRequest failed to initiate.");
}
httpReq.onreadystatechange = function() {

    var failTimer = setTimeout(function() {
                               failed = true;
                               httpReq.abort();
                               }, max);

    if (httpReq.readyState == 4) {  //Completed loading
        if (!failed && (httpReq.status == 200 || httpReq.status == 0)) {

            clearTimeout(failTimer);

            t2 = Date.now();

            var timeTotal = (t2 - t1);
            if(timeTotal > max) {
                onFail();
            } else {
                onSuccess(timeTotal);
            }

        }
        else {  //Otherwise, there was a problem while loading
            console.log("Error " + httpReq.status + " has occurred.");
            onFail();
        }
    }
}
try {
    httpReq.open("GET", address, true);
    httpReq.send(null);

} catch(e) {
    console.log("Error retrieving data httpReq. Some browsers only accept cross-domain request with HTTP.");
    onFail();
}


function onSuccess(timeTotal) {

    alert("Time needed to connect: " + timeTotal);
}
function onFail() {
    alert("Well this isn't good");
}

An iframe may be a viable solution as well though.



来源:https://stackoverflow.com/questions/8469249/how-to-check-if-site-is-online-with-javascript-plus-tips-on-how-to-make-the-res

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!