1

I'm creating an HTML autorun. There is no restriction in using javascript as it will be run from XULRunner. I want a way to detect if internet connection exist or not. This doesn't work for me

$(document).ready(function() {
    var online = navigator.onLine;

// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
function doit() {
if (navigator.onLine(connected)){     
alert("YES!");
} else {    
 alert("NO!"); 
}  
} 

Is there a better way?

Update: Came to know that the code above only detects the browser state and not if internet is available. For me the contact form in the autorun has to check if internet is connected and alert the user.

esafwan
  • 17,311
  • 33
  • 107
  • 166
  • possible duplicate of [JavaScript: How to detect that the Internet connection is offline?](http://stackoverflow.com/questions/189430/javascript-how-to-detect-that-the-internet-connection-is-offline) – Marko Oct 23 '10 at 05:06
  • but it doesn't answer my question. :( – esafwan Oct 23 '10 at 05:43
  • it is just if(navigator.onLine) and the link to the duplicate seems to contain all the answers you are going to get. – mplungjan Oct 23 '10 at 09:34
  • no .onLine is not a solution for me. It only detects the browser state it seems. – esafwan Oct 24 '10 at 09:59

1 Answers1

2

Use an XMLHttpRequest in javascript to request a small file from your server. If the request returns an error or times out, then the site is probably unreachable. If you don't have a particular webserver to test on, you could use something with a high degree of reliability, like the Google server.

Though, if you do use the Google server that wouldn't necessarily correspond to your own site being reachable, it would just mean that you are able to connect to the internet. Your own site may down\otherwise unavailable.

mechanarchy
  • 167
  • 1
  • 7
  • how do you use gmail server for this ... since ajax will only support in your own domain jquery policy The JQuery documentation has a section on handling failed AJAX requests. the Same Origin Policy when doing this, can stop you from accessing sites outside your domain. – Hitesh Aug 27 '13 at 12:07