使用JS在浏览器中判断当前网络连接状态的几种方法

JavaScript09

使用JS在浏览器中判断当前网络连接状态的几种方法,第1张

通过navigator.onLine判断当前网络状态:

if(navigator.onLine){

...}else{ ...}

非常简单,但是并不准确-根据MDN的描述:

navigator.onLine只会在机器未连接到局域网或路由器时返回false,其他情况下均返回true。

也就是说,机器连接上路由器后,即使这个路由器没联通网络,navigator.onLine仍然返回true。

正常情况下,其它浏览器能够自动检测是否具有网络链接,但是 google 浏览器在这个方面有 BUG,很多网站采用的一种做法是不断的向服务器发送请求,确保连接的稳定,如果连不上了,就说明网络断开了,所以你的问题就可以采用类似的办法,下面是 js 代码:

function isOnline(){

  var img = new Image()

  img.id = "test_is_online"

  img.onload = function(){

    document.body.removeChild(

         document.getElementById("test_is_online"))

  }

  img.onerror = function(){

    document.body.removeChild(

        document.getElementById("test_is_online"))

    alert("断网了!")

  }

  img.src = "http://www.baidu.com/img/baidu_jgylogo3.gif"

  img.style.display = "none"

  document.body.appendChild(img)

}

window.onload = function(){

    setInterval(isOnline, 10000)

}

每 10 秒钟检测一次,如果发现已经断网了,就会弹出对话框说:断网了