纯js实现判断ip是否ping通

1,217 阅读1分钟

最近在做一个需求时要考虑到网络环境是否能够访问,于是写了一段代码,原理是根据是否能访问某一网址来判断对应的网络环境是否可以访问到

    function ping(address) {
      var img = new Image();
      var start = new Date().getTime();
      var hasFinish = false;
      img.onload = function() {
        if ( !hasFinish ) {
          hasFinish = true;
          console.log('Ping ' + address + ' success. ');
        }
      };
      img.onerror = function() {
          hasFinish = false;
          console.log('Ping ' + address + ' fail.. ');
      };
      img.src = address + '/?' + start;
      setTimeout(()=>{
        if(hasFinish){
          hasFinish = false
          console.log('There is a problem with your network, please refresh the page and try again.');
        }
      },1500)
    }
   ping('https://developers.facebook.com/favicon.ico')