js 检测是否断网

JavaScript08

js 检测是否断网,第1张

navigator.onLine

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

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

正常情况下,其它浏览器能够自动检测是否具有网络链接,但是 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 秒钟检测一次,如果发现已经断网了,就会弹出对话框说:断网了