I basically follow the accepted answer to this question ( Is it possible to execute a ping server with Javascript? )
Update
It seems to work as expected when a domain lasts 15 characters (actually, http: // + 15, but 16 or more makes it bomb. For more details see below.
The problem that I see is that if you use something similar to a valid domain, for example http://thisisdefinitelynotarealdomainname.com, it returns an error, but the code mentioned considers the errors in order (because most should be). If you look at the error event, I'm not sure I see where I can get the HTTP response code (i.e., if it is 404, consider it invalid).
Here is a jsFiddle showing the problem - they all display "answered". If you look at the console, an invalid domain returns a 404 error, and two valid ones (if the console is chrome, unsure of others) show that they were interpreted as an image, but transmitted as text / html - is there any way to read or a 404 error , or type mime?
var pinger = function () {
var ping = function (ip, callback) {
if (!this.inUse) {
this.status = 'unchecked';
this.inUse = true;
this.callback = callback;
this.ip = ip;
var _that = this;
this.img = new Image();
this.img.onload = function () {
_that.inUse = false;
_that.callback('responded');
};
this.img.onerror = function (e) {
if (_that.inUse) {
_that.inUse = false;
_that.callback('responded', e);
}
console.log(e);
};
this.start = new Date().getTime();
this.img.src = "http://" + ip + "/?now=" + this.start;
this.time = setTimeout(function () {
if (_that.inUse) {
_that.inUse = false;
_that.callback('timeout');
}
}, 1500);
}
}
return {
ping: ping
};
}();
(function () {
var output = document.getElementById('output');
var servers = [
'localhost',
'google.com',
'okthisreallydoesntmakeanysense',
'okthisreallydoe',
'thisisashortone',
'thisisabitlonger'
];
servers.forEach(function (server) {
new pinger.ping(server, function (status, e) {
output.innerHTML += server + ': ' + status + '<br />';
});
});
})();
Update
What is even stranger is that it looks up to 15 characters. I updated jsFiddle . See below for those who respond, as I expect, against those who do not. What can cause this?
'localhost',
'google.com',
'okthisreallydoesntmakeanysense',
'okthisreallydoe',
'thisisashortone',
'thisisabitlonger'