如何检测导航器是否将您的状态更改为在线/离线?
就像是:
var oldState = navigator.onLine;
window.navigator.onlinechange = function(evnt,newState) {
alert('your changed from' + oldState + ' to' + newState + 'state');
}
如何检测导航器是否将您的状态更改为在线/离线?
就像是:
var oldState = navigator.onLine;
window.navigator.onlinechange = function(evnt,newState) {
alert('your changed from' + oldState + ' to' + newState + 'state');
}
借助 body 上的类和此代码,您可以找到
window.ononline = function() {
alert('You are now online');
}
window.onoffline = function() {
alert('You are now offline');
}
像这样(不是每个浏览器都支持这些事件,目前只有 IE 8,9 和 FF > 3 支持这些事件):
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");};
}
浏览器支持各不相同,请查看:http ://help.dottoro.com/ljnasgpu.php
如果它需要更多的跨浏览器兼容,您必须轮询 navigator.onLine 属性。
var status = document.getElementById('status')
setInterval(function () {
status.innerHTML = navigator.onLine ? 'online' : 'offline';
}, 250);