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
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 ...Dropping Support for Internet Explorer 6
2:37p.m., 11 Oct
Microsoft's Internet Explorer 6 has long been the bane of every front-end developer's life. It's a 10-year old browser - ...Xfm Buzz - A Radio Hack
1:15p.m., 31 May
At Global Towers we developers have 10% time to go away and hack at something that might, ultimately, bring value ...Converting A Word Doc Into A Kindle E-Book
5:49p.m., 19 May
Last week Emma decided to publish her novel "Unfamous" as an e-book on Amazon's Kindle store. Converting the book into ...