Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
function hostReachable() {
// Handle IE and more capable browsers
var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );
var status;
var server = window.location.hostname;
if (window.location.port != '') {
server += ':'+window.location.port;
}
// Open new request as a HEAD to the root hostname with a random param to bust the cache
xhr.open( "HEAD", "//" + server + "/?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;
}
}
@Hettomei

This comment has been minimized.

Copy link

@Hettomei Hettomei commented Sep 29, 2014

Because I m not good at javascript, I'd like to ask you why you prefer :

 if (window.location.port != '') {
  server += ':'+window.location.port;
}

instead of:

window.location.host

is there any fail with window.location.host ?

@michaellopez

This comment has been minimized.

Copy link

@michaellopez michaellopez commented Dec 23, 2014

@Hettomei The XHR request needs to be sent to the server. If the server is listening on port 8080 for example, a request to a hostname without port 8080 will not give you a response.

@ali-master

This comment has been minimized.

Copy link

@ali-master ali-master commented Mar 8, 2017

it's Great, Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.