Check internet connection

-1

I would like to know how to check the internet connection using Java Script.

Example: If the internet is unavailable, one appears with a warning message, if the internet is available, one appears loading a page.

    
asked by anonymous 09.09.2017 / 21:09

2 answers

2

You can use navigator.online , it returns a boolean on your connection to intenet:

var online = navigator.onLine;

Using alert :

alert(navigator.onLine == true ? "Conexão OK" : "Você não possui conexão com a internet");

Using console.log :

console.log(navigator.onLine);
    
09.09.2017 / 21:16
0

You can use Ping requests using Ajax for another server and test for a connection to it, you can use your same server, or use another server :

// Importa o JQuery
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script>
function ping(host, port, pong) {
  var started = new Date().getTime();
  var http = new XMLHttpRequest();

  http.open("GET", "http://" + host + ":" + port, /*async*/true);
  http.onreadystatechange = function() {
    if (http.readyState == 4) {
      var ended = new Date().getTime();
      var milliseconds = ended - started;
      if (pong != null) {
        pong(milliseconds);
      }
    }
  };
  try {
    http.send(null);
  } catch(exception) {
    // erro na conexão
  }
}
    
    ping("google.com", "80", function(m){ console.log("Levou "+m+" millisegundos."); })
    
    </script>

Source of the response .

    
09.09.2017 / 21:23