javascriptajaxofflineconnectivityinternet-connection

Detect if the internet connection is offline?


How can I detect if the internet connection is offline in JavaScript?


Solution

  • Almost all major browsers now support the window.navigator.onLine property, and the corresponding online and offline window events. Run the following code snippet to test it:

    console.log('Initially ' + (window.navigator.onLine ? 'on' : 'off') + 'line');
    
    window.addEventListener('online', () => console.log('Became online'));
    window.addEventListener('offline', () => console.log('Became offline'));
    
    document.getElementById('statusCheck').addEventListener('click', () => console.log('window.navigator.onLine is ' + window.navigator.onLine));
    <button id="statusCheck">Click to check the <tt>window.navigator.onLine</tt> property</button><br /><br />
    Check the console below for results:

    Try setting your system or browser in offline/online mode and check the log or the window.navigator.onLine property for the value changes.

    Note however this quote from Mozilla Documentation:

    In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet. You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking.

    In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. Until Firefox 41, all other conditions return a true value; since Firefox 41, on OS X and Windows, the value will follow the actual network connectivity.

    (emphasis is my own)

    This means that if window.navigator.onLine is false (or you get an offline event), you are guaranteed to have no Internet connection.

    If it is true however (or you get an online event), it only means the system is connected to some network, at best. It does not mean that you have Internet access for example. To check that, you will still need to use one of the solutions described in the other answers.

    I initially intended to post this as an update to Grant Wagner's answer, but it seemed too much of an edit, especially considering that the 2014 update was already not from him.