Detect change on navigator.online

How can I determine if the navigator has changed your status to online / offline?

sort of:

var oldState = navigator.onLine; window.navigator.onlinechange = function(evnt,newState) { alert('your changed from' + oldState + ' to' + newState + 'state'); } 
+4
source share
3 answers

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");}; } 

Browser support is changing, check this out: http://help.dottoro.com/ljnasgpu.php

+4
source

If it should be more browser compatible, you need to query the navigator.onLine property.

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

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

+2
source

With classes on the body and this code, you can find

 window.ononline = function() { alert('You are now online'); } window.onoffline = function() { alert('You are now offline'); } 
+1
source

All Articles