1

I have the following listener for checking if the user has an active internet connection:

$(function() {  
$( window ).bind(
        "online offline",
        function( event ){
          console.log("-------------------window bind------------------------------");
            if(hasInternets()){
                console.log("window bind online---------------------------------------------");
                sendAllPendingData();
            }else {
                console.log("window bind offline--------------------------------------------");
            }
        }
        );


});

function hasInternets() {
    console.log("hasInternets: " + window.location.href.split("?")[0] + "?" + Math.random());
    var s = $.ajax({ 
        type: "HEAD",
        url: window.location.href.split("?")[0] + "?" + Math.random(),
        async: false
    }).status;
        console.log("s: " +s);
    //thx http://www.louisremi.com/2011/04/22/navigator-online-alternative-serverreachable/ 
    return s >= 200 && s < 300 || s === 304;
}

It works fine in my laptop. I'm not sure if it works fine on other machines and devices. I'm not knowledgeable in this stuff. So will really appreciate it if anyone can advise. And by the way, while I'm doing my research, I stumbled upon this TrueOnline on the jquery plugin, have anyone tried this? http://archive.plugins.jquery.com/project/trueonline

Thanks.

lorraine batol
  • 6,001
  • 16
  • 55
  • 114
  • possible duplicate of [Check if Internet Connection Exists with Javascript?](http://stackoverflow.com/questions/2384167/check-if-internet-connection-exists-with-javascript) < might help > **`:)`** – Tats_innit Jul 18 '12 at 09:05
  • Hi, tats. Thanks for the reply. But I'm afraid I need a listener for offline/online events, not just for checking if the user is online/offline on page loads. – lorraine batol Jul 18 '12 at 15:23

1 Answers1

0

The online & offline events are part of HTML5, and so will not work on older browsers.

To support these browsers, you should launch hasInternets() periodically (e.g. via setInterval), and respond accordingly to whether the response was successful.

You could also be aware of window.navigator.onLine, but note the incredible amount of browser variations/ bugs; so it's a property I'd try to avoid.

Matt
  • 74,352
  • 26
  • 153
  • 180
  • Hi, Matt. Thanks for the reply. Yeah, I've read about the navigator.onLine stuff, it's unreliable, so I tried using the above code instead, ajax telling me if my domain is accessible (which means I have internet connection). Can you post some code or maybe point me to a tutorial on having the hasInternets() called continuously. Thanks – lorraine batol Jul 18 '12 at 15:22