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.
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.
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);
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 .