-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.
-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.
2
You can use the navigator.online, he returns a Boolean about his connection to the intenet:
var online = navigator.onLine;
Using the alert:
alert(navigator.onLine == true ? "Conexão OK" : "Você não possui conexão com a internet");
Using the console.log:
console.log(navigator.onLine);
0
You can use requests Ping using Ajax to another server and test if there is a connection with 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 reply.
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.