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.
well, you can try the javascript plugin which can monitor the browser connection in real time and notifies the user if internet or the browsers connection with the internet went down.
Wiremonkey Javascript plugin and the demo you can find here
The
window.navigator.onLine
attribute and its associated events are currently unreliable on certain web browsers (especially Firefox desktop) as @Junto said, so I wrote a little function (using jQuery) that periodically check the network connectivity status and raise the appropriateoffline
andonline
event:You can use it like this:
To listen to the offline and online events (with the help of jQuery):
I use the FALLBACK option in the HTML5 cache manifest to check if my html5 app is online or offline by:
In the html page i use javascript tot read the contents of the online/offline txt file:
When offline the script will read the contents of the offline.txt. Based on the text in the files you can detect if the webpage is online of offline.
you can detect offline cross-browser way easily like below
you can replace yoururl.com by
document.location.pathname
.The crux of the solution is, try to connect to your domain name, if you are not able to connect - you are offline. works cross browser.
Using Document Body:
Using Javascript Event:
Reference:
Document-Body: ononline Event
Javascript-Event: Online and offline events
Additional Thoughts:
To ship around the "network connection is not the same as internet connection" Problem from the above methods: You can check the internet connection once with ajax on the application start and configure an online/offline mode. Create a reconnect button for the user to go online. And add on each failed ajax request a function that kick the user back into the offline mode.
have you tried using service workers? http://www.html5rocks.com/en/tutorials/service-worker/introduction/