Janx from Venezuela
Janx from Venezuela

Reputation: 1197

Check for internet connection on Javascript

Ok, I got this case. I got this app build on angular.js with a back-end build on node.js ... it works fine by all means.

The client got a crappy connection to the internet. It goes online and offline every now and then. What I need to do is a routine that pings my server to check for connection on it. If it fails, I need to ping to something else (lets say : google.com) so I can check two things:

1.- My server is online (or not) 2.- The client has no internet connection.

Ping to server works fine using this routine:

function hostReachable(host) {  // Handle IE and more capable browsers 
    var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" ); 
    var status;  
    // Open new request as a HEAD to the root hostname with a random param to bust the cache 
    xhr.open( "GET", "//" + host + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);  
    // Issue request and handle response 
    try { xhr.send(); return (xhr.status >= 200 && xhr.status < 300 || xhr.status === 304); }
    catch (error) { return false; }
    }
 }

function check() {
if (!hostReachable(window.location.host)) {
    if (!hostReachable('www.google.co.ve')) {
        alert('No se pudo establecer conexión con el sistema. Revise su conexion a internet.');
    } else {
        alert('Existe un problema con el sistema. Por favor contacto a los administradores.');
    }
} else {
    console.log('Connected...');
}
}

check();

The deal is that checking google.com goes with cross-domains problems. so the question is very simple. Is there a way to check for internet connectivity like this ?

Upvotes: 0

Views: 1410

Answers (2)

dansalmo
dansalmo

Reputation: 11694

You could try making a request for a javascript resource from google or some other highly reliable cdn. It would not be subjected to cross-domain restrictions.

Upvotes: 1

user3886234
user3886234

Reputation:

If you send a cross-domain request and the server you are trying to ping against doesn't accept it, they will send back an access-denied status. I think that is 403, but you would want to check firebug / chrome dev tools to see what the actual code is. Then, if you get that code, you know at the very least the request was sent and a response was received.

--edit--

Here is an example of what I mean on JSFiddle. Be sure to check the network requests on chrome dev tools / firebug. It is sending a request to www.google.com, and receiving a 404 status code in the response.

Sidenote: As it turns out, different servers send back different codes when denying cross-domain requests. It seems 401, 403, and 404 are the most popular ones. For anyone looking at this problem in the future, you will want to check which codes the site(s) you ping against are sending back.

Upvotes: 3

Related Questions