2

I have an app with an embedded IE 7 browser. I need to test in a static HTML page, javascript is okay, whether the user has a connection to the Internet.

Offline.js though an excellent library will not work here because the javascript is not supported.

The window.navigator.onLine object.property does not exist.

Simply using a meta redirect is not an option because if the internet is not accessible I will be leaving the user on the current page. The logic should look something like this:

function UserIsOnlineTest(){
// needed code goes here
// boolean return value
}

if (UserIsOnlineTest()) {
  window.location.replace('http://theOnlineSite.com/');
}

Thoughts?


The complete solution I ended up with (based on @RobM. answer)

(function(){

    var testImage= 'http://the.site.com/testimage.png';
    var image = new Image();
    var online = true;
    image.src = testImage;
    image.onerror = function() {
       online = false;
    }

    setTimeout(function() {
        if (online) {
            window.location.replace('http://the.site.com/');
        },1000);
    }

}());

Even more finalized, I needed to add a delay in the test for the error. Since this was the practically the only code in the file it was actually testing the online variable before the image was downloaded.

THBBFT
  • 1,161
  • 1
  • 13
  • 29

1 Answers1

1

If you have an image that you know should be online, you can create an image tag and have onerror indicate that the user is offline:

var googleLogo = 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
var image = new Image();
image.src = googleLogo;
image.onerror = function() {
   // user is offline
}
Rob M.
  • 35,491
  • 6
  • 51
  • 50
  • Wouldn't it be more efficient to just make an XHR request to something that *should be online* ? – Tim van Osch Aug 04 '16 at 20:37
  • 1
    I cannot make xhr request from the embedded IE7 control. It errors out telling me the script is not accessible. – THBBFT Aug 04 '16 at 20:39
  • "efficient" in what way? I would imagine (nothing to back this up) that there is less overhead in an image request than an XHR request, but if anything I would call it a toss up – Rob M. Aug 04 '16 at 20:39