I'm trying to accurately detect when the browser goes offline, using the HTML5 online and offline events.
Here's my code:
<script>
// FIREFOX
$(window).bind("online", applicationBackOnline);
$(window).bind("offline", applicationOffline);
//IE
window.onload = function() {
document.body.ononline = IeConnectionEvent;
document.body.onoffline = IeConnectionEvent;
}
</script>
It works fine when I just hit "Work offline" on either Firefox or IE, but it's kind of randomly working when I actually unplug the wire.
What's the best way to detect this change? I'd like to avoid repeating ajax calls with timeouts.
navigator.onLine is a mess
I face this when trying to make an ajax call to the server.
There are several possible situations when the client is offline:
The solution I am using is to control the status myself with javascript. I set the condition of a successful call, in any other case I assume the client is offline. Something like this:
The browser vendors cannot agree on how to define offline. Some browsers have a Work Offline feature, which they consider separate to a lack of network access, which again is different to internet access. The whole thing is a mess. Some browser vendors update the navigator.onLine flag when actual network access is lost, others don't.
From the spec:
Finally, the spec notes:
The best way which works now on all Major Browsers is the following Script:
Source: http://robertnyman.com/html5/offline/online-offline-events.html