How to detect an offline state on a web page?

64 3

To do a web web app, how to detect the offline state?
Think that you can initiate ajax requests at a time, depending on the return state.
There's a simpler alternative.

2 Answers

94 4

Html5 scenarios

if (navigator.onLine) {
 console.log('ONLINE!');
} else {
 console.log('Connection flaky');
}
window.addEventListener('online', function(e) {
//Re-sync data with server.
}, false);
window.addEventListener('offline', function(e) {
//Queue up events for server.
}, false);
60 5

Html5 scenarios

if (navigator.onLine) {
 console.log('ONLINE!');
} else {
 console.log('Connection flaky');
}
window.addEventListener('online', function(e) {
//Re-sync data with server.
}, false);
window.addEventListener('offline', function(e) {
//Queue up events for server.
}, false);
...