Skip to Content

Gareth53.co.uk - the online home of Gareth Senior

Detecting Online Status In The Browser

11:55a.m., Mon 28 Nov 2011

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

Blog Categories