Skip to content

Instantly share code, notes, and snippets.

@jpsilvashy
Forked from louisremi/serverReachable.js
Last active November 10, 2020 09:59
Show Gist options
  • Save jpsilvashy/5725579 to your computer and use it in GitHub Desktop.
Save jpsilvashy/5725579 to your computer and use it in GitHub Desktop.
function hostReachable() {
// 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( "HEAD", "//" + window.location.hostname + "/?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;
}
}
@davidwwu
Copy link

davidwwu commented Aug 16, 2016

// Open new request as a HEAD to the root hostname with a random param to bust the cache << Why do you have to bust the cache? And how is it going to bust the cache? Thanks!

@mhdSid
Copy link

mhdSid commented Sep 14, 2017

And if you want to wait until online you can use this:

public waitUntilOnline(): any {

        return new window.Promise((resolve, reject) => {  

        	let interval: any = window.setInterval(() => {   

        		if (this.isOnline()) {   

        			window.clearInterval(interval);  
 
        			interval = undefined;   

        			resolve(true); 
  
        		}  else {   

        			console.log('Browser is still offine...');  
 
        		}   

        	}, 2500);   

        });   
}

this.waitUntilOnline().then((isOnline: boolean) => {
 //always returns true here. Do anything when the browser switches from offline to online
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment