0

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 ?

7
  • Is there any appreciable difference for the end user? Are you wanting them to email you and tell you your server is offline so you can restart it? Commented Aug 19, 2014 at 23:59
  • 1
    navigator.online outmodes your first task. Commented Aug 20, 2014 at 0:00
  • @dandavis—according to MDN, navigator.onLine isn't particularly reliable and a backup method (e.g. per the OP) should be employed. Commented Aug 20, 2014 at 1:11
  • @RobG: it's very reliable that if navigator.online===false, you don't have internet. if it's true, then the OP's 2nd step should handle the potential false positives. Commented Aug 20, 2014 at 1:15
  • you can use xhr.onerror() to avoid the try/catchy yuckiness. Commented Aug 20, 2014 at 1:17

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

It won't send status. I falls back right to the catch statement after xhr.send().. with an error that says something like "failed to execute send on XMLHttpRequest: failed to load google.com/?rand=123412"
@JanxfromVenezuela I added a JSFiddle example. If you get a 40X response, it logs an error to the console but doesn't actually break the script's flow.
In your fiddle example, you're trying to GET fiddle.jshell.net/_display/www.google.com and it returns 404. If you change the way you do xhr.open to : ('GET', "//" + url + , true), then you will be actually pinging google, and it will fail on xhr.send() because No 'Access-Control-Allow-Origin' header is presen t on the requested resource, therefore not allowed access.
1

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.

2 Comments

Because ? ... I tryed code.jquery.com/jquery-1.11.1.js instead of google.com and the same no 'Access-Control-Allow-Origin' header problem is there.!
Well, it turns out you can request, lets say from netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css. Don't know if it's because is a CSS file instead of a JS file (don't think so really), but anyways, it works.!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.