detect change on navigator.online

扶醉桌前 提交于 2019-12-05 08:12:06

Something like this (not every browser supports these events, currently only IE 8,9 and FF > 3 support these events):

var el = document.body;
if (el.addEventListener) {
   el.addEventListener("online", function () {
     alert("online");}, true);
   el.addEventListener("offline", function () {
     alert("offline");}, true);
}
else if (el.attachEvent) {
   el.attachEvent("ononline", function () {
     alert("online");});
   el.attachEvent("onoffline", function () {
     alert("offline");});
}
else {
   el.ononline = function () {
     alert("online");};
   el.onoffline = function () {
     alert("offline");};
}

The browser support varies, check this out: http://help.dottoro.com/ljnasgpu.php

With the help of classes on body and this code you can find

window.ononline = function() {
    alert('You are now online');
}

window.onoffline = function() {
    alert('You are now offline');
}

If it needs to be more cross browser compatible you have to poll the navigator.onLine property.

var status = document.getElementById('status')

setInterval(function () {
  status.innerHTML = navigator.onLine ? 'online' : 'offline';  
}, 250);

Demo: http://html5demos.com/nav-online

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