js 检测是否断网

JavaScript012

js 检测是否断网,第1张

navigator.onLine

online和offline。当网络从离线变为在线或者从在线变为离线时,分别触发这两个事件。这两个事件在window对象上触发。(必须要手工轮询这个属性才能检测到网络状态的变化。 )

Offline.js 插件( https://github.com/hubspot/offline )

通过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 秒钟检测一次,如果发现已经断网了,就会弹出对话框说:断网了