12

How to check if there is an internet connection in Javascript? I have searched in Google but I have not found a good solution for my problem.

I have already got two eventhandler:

document.body.addEventListener("offline", function () {
    //alert("offline")
    masterViewModel.online(false)
}, false);
document.body.addEventListener("online", function () {
    //alert("online")
    masterViewModel.online(true);
}, false);

But how to check in the "onload"-function if I am online?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
spitzbuaamy
  • 751
  • 2
  • 10
  • 25

4 Answers4

28

In HTML5, according to the specs:

var online = navigator.onLine;
UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
3

Hi You can do like this:

var connectionMessage = "internet connection";
var noConnectionMessage = "No internet connection.";
window.onload = checkInternetConnection;
function checkInternetConnection() {
  var isOnLine = navigator.onLine;
   if (isOnLine) {
      alert(connectionMessage);
   } else {
     alert(noConnectionMessage);
   }
}
ravisolanki07
  • 637
  • 3
  • 13
3

var online = navigator.onLine; is doesn't work every time.Sometime your connection is enabled but you can not fetch data from internet or not access a site even if you are online...so that time online return true because you are online.that time "navigator.onLine" is not usable.

" You could be getting false positives, such as in cases where the computer is running a virtualization software that has virtual ethernet adapters that are always "connected." Therefore, if you really want to determine the online status of the browser, you should develop additional means for checking. To learn more, see the HTML5 Rocks article, " check this article

you must use ajax request to check....

Parth Chavda
  • 1,819
  • 1
  • 23
  • 30
0

Why not just make an ajax call to a well-known address, say StackOverflow. If you don't get 404, you are online.

user1556718
  • 91
  • 1
  • 9