There are a number of ways to do this:
- AJAX request to your own website. If that request fails, there's a good chance it's the connection at fault. The JQuerydocumentation has a section on handling failed AJAX requests. Beware of the Same Origin Policy when doing this, which may stop you from accessing sites outside your domain.
-
You could put an
onerror
in animg
, like<img src='http://www.example.com/singlepixel.gif'
onerror='alert("Connection dead");' />This method could also fail if the source image is moved / renamed, and would generally be an inferior choice to the ajax option.
So there are several different ways to try and detect this, none perfect, but in the absence of the ability to jump out of the browser sandbox and access the user's net connection status directly, they seem to be the best options.
IE 8 will support the window.navigator.onLine property.
network: function() {
var state = navigator.onLine ? "online" : "offline";
return state;
}