Detecting Online Status In The Browser
I was just heading into a meeting when I was asked how our (mostly web-based) iOS application was going to handle a loss of connectivity.
People were slow to arrive to the meeting, so I wrote the code while I waited. It was remarkably simple and worked (in Google Chrome) first time.
Testing it involved switching my laptop's airport on/off. The browser event fired a few secondss later - the online event seemed to take a little longer to respond than the offline event, but that might just be my perception.
Once I got out of the meeting and did a little in-depth googling I found a handful of scripts that were incredibly similar to mine. Mine's namespaced though, so I thought it worth sharing.
There's a demo of the code here.
ConnStatus = {
init: function() {
ConnStatus.update_status();
window.addEventListener('online', function(){
ConnStatus.update_status();
});
window.addEventListener('offline', function(){
ConnStatus.update_status();
});
},
update_status: function() {
var status = (window.navigator.onLine) ? 'Online' : 'Offline';
var statusObj = document.getElementById('status');
statusObj.innerHTML = status;
statusObj.setAttribute("class", status.toLowerCase());
}
};
window.onload = function() {
ConnStatus.init();
}
Browser Support
I mentioned earlier that this worked in Google Chrome. Browser support elsewhere seems to be patchy. In Firefox the events fired when I manually toggled offline mode on and off, but just pulling my network cable or toggling airport mode didn't trigger the events. Safari 5 returned true for window.navigator.onLine whatever I did and I couldn't get the events to fire either. Opera 11.5 correctly reported the onLine status based on the 'Work Offline' setting but didn't respond to the window events. As far as I can see though, the Google Chrome behaves as I expected and behaves as I interpret the standards so here's hoping that other browsers follow that behaviour.
Remy Sharp and Schalke have more details on the state of the spc and of browser support.
More information
Latest Posts
New Launch: Global Radio App
5:35p.m., 3 Sep
The new Global Radio App for iPhone and iPad was released a little over two weeks ago (20 August) and ...How The sort() Method Of An Array Works
1:17p.m., 2 Dec
... or "What I What I Learned from the Exercise In Futility, Part 2". (This follows on from my earlier ...Custom Constructor With An Unknown Number of Arguments
10:19p.m., 30 Nov
...or "What I What I Learned From An Exercise In Futility, Part 1" - how to enforce the 'new' keyword ...Muppets Birthday Card
5:47p.m., 28 Nov
Emma loves The Muppets. She even has her own Muppet who we call Emma Too and who was born at ...