Search code examples
javascriptfirefox-os

How to check if Firefox OS is connected to the internet or not


How do we check if Firefox OS device is connected to the internet or not? I have tried navigator.mozConnection, navigator.connection.type, navigator.onLine but it doesn't work.

Please let me know. Thanks.


Solution

  • What Peter suggested is possible, although it isn't classy or follows best practices.

    I'm complementing Jason Weathersby answer by providing some code example and how this can be achieved.

    Browser Behavior

    This is a very browser-dependant implementation, you should be cautious by using those properties. As outlined in MDN,

    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

    Which means that you can be connected to a LAN without internet access and still have it returning true.

    In Firefox and Internet Explorer, switching the browser to offline mode sends a false value. All other conditions return a true value.

    If the browser doesn't support navigator.onLine the above example will always come out as falsy (false/undefined).

    Code Sample

    To check if the you have connection, try online = window.navigator.onLine;

    If you want to listen on connection changes, you should do something like

    When connection is turned off

    window.addEventListener("offline", function(e) {do something})

    When connection is back on

    window.addEventListener("online", function(e) {do something})

    Other suggestions

    Those solutions can be unreliable, so there are a few fallbacks on this if you want to be on safe grounds here. As http://www.html5rocks.com/en/mobile/workingoffthegrid/ shows, you can try doing something like

    window.applicationCache.addEventListener("error", function(e) { alert("Error fetching manifest: a good chance we are offline"); });

    The reason why this works, is because it always makes an attempt to request the manifest to check to see if it needs to update its list of assets. If that requests fails it is normally one of two things, the manifest file is no longer being used (that is, it is not hosted) or the system is unable to access the network to fetch the file.