How to: detect internet connection in Javascript
I am working on a project currently that involves content being delivered for offline use, with no certainy an internet connection will be present.
There's a feedback form, and since forms need a PHP (or other) handler to receive and process the post data, the form was to be available only if a connection was present and the handler could be loaded.
Which led me innevitably to the question: how to check for an internet connection in JS?
AJAX springs to mind, but there's the Same Origin Policy just waiting to trip you up on that one. Yes, you could have your AJAX request call a PHP script which, through something like cURL(), can check for a remote connection, but not if you don't have PHP in the environment.
Eventually I opted on a very simple technqiue, but which appears safe: run a native, DOM-zero onload event on a remote image.
The obvious - and only - risk here is that if the site hosting the image was down, your JS script would think there was no internet connection.
So load an image on the site whose remote assets you need to call (in my case, the PHP handler). If that's down, then it amounts to the same thing as there being no internet connection, as either way your handler won't be loaded.
Here's the code involved:
1var img = document.createElement('img');
2img.src = "http://www.somesite.com/myimage.jpg";
3var connection = false;
4img.onload = function() { connection = true; }
You can subsequently check for a connection by querying the boolean connection.
That's fine if your code is in a function and invoked by an event some time after load, but if it's JS that's set to run automatically, you'll need to delay it a few seconds at least to make sure the image load request has had chance to run.
In which case, put your code in a setTimeout() callback, e.g.
1setTimeout(function() {
2 /* your code here
3 ...
4 etc */
5}, 3000); //your code waits 3 seconds then runs
Comments (3)
Chuks, at 12/12/'11 00:18, said:
Mitya, at 12/12/'11 16:05, said:
philp kauffman, at 14/08/'12 04:24, said: