navigator.onLine alternative: serverReachable()

Remy Sharp blogged recently about the issues of the navigator.onLine property and online/offline events. Let see how they can be worked around.

Getting the browser to handle it is hard

As it turns out, this property and those events can currently only be relied on to tell whether and when the user decides to turn on/off the “Work offline” feature of the browser. Indeed, some platforms have specific behaviors that make it hard for the browser to be constantly aware of the computer connectivity: Windows sometime incorrectly report its connectivity after waking up from hibernation, NetworkManager on Linux can’t be trusted because some users bypass it, etc.
This is why, as of Firefox4 and until we can find a reliable alternative, only the user can switch to offline mode.

What onLine doesn’t tell

If you are building a website with offline features, using this property to switch between online and offline mode might not be the best option. Not only can it incorrectly report the connectivity of the computer, but it also doesn’t tell anything about the actual reachability of the server: you might be connected to a network blacklisting the service; you might have no connection but be developing a website locally; or the server could be down…

In any case, it is probably more reliable to simply send a request to the server and fallback to local storage/resources/database when the request fails.


Following is an example of code you can use to verify that the server is reachable

5 thoughts on “navigator.onLine alternative: serverReachable()

  1. Frank Yan

    “Requesting the headers is faster, and just enough”: I had forgotten about that option; thanks for the reminder!

    Also, |”//” + window.location.hostname + “/?rand=” + Math.random(),| could be replaced with |”/?” + +new Date,|.

  2. Jay Fienberg

    This is useful and interesting. I’ve been trying to see if I could use appcache to serve a failover scenario such that, when a website is down, returning visitors see either an offline page and/or are redirected to a mirror site.

    I’m not having much luck with appcache alone due to some of the issues you mention in your previous post. But, this serverReachable() method helps. It’s actually working pretty well in Safari.

  3. Scott Jehl

    This is great, nice work! However, I think it’ll return false when testing on localhost. It may be due to the protocol-relative url, but I get a “0″ xhr status when testing locally.

    I used the following url instead, which seems to work around the issue:
    window.location.href.split("?")[0] + "?" + Math.random()

    For reference, I’d been using it in this jQuery-dependent version:

    Thanks again.

  4. Pingback: JavaScript/Ajax: navigator.onLine alternative: serverReachableCode and Programming

Comments are closed.