How to detect if the server shut down during the client has visited a page with javascript?
A request with a forever keep-alive header could do it, but the problem is that fires even when the user navigates away from the page.
How to detect if the server shut down during the client has visited a page with javascript?
A request with a forever keep-alive header could do it, but the problem is that fires even when the user navigates away from the page.
Perhaps this is a bit of a naive approach, but you could count the number of response headers when an ajax call fails. With jQuery, for instance, you could do this:
$.ajax( {
'url': urlToTheServer,
'success': function()
{
// server is up
},
'error': function( $xhr )
{
if( $xhr.getAllResponseHeaders().length < 1 )
{
// fair probability server is down
}
}
} );
The way I tested this, on my development box, is wrap the above in a setTimeout()
call (with say, a 10 sec. timeout). Load the page. Shutdown server. And then wait for the timeout to expire and do the ajax request.
PS.: $xhr.getAllResponseHeaders()
returns a newline delimited string of headers, not an array or object of headers. I overlooked this at first, however, this doesn't change the outcome of the script. If the string length of $xhr.getAllResponseHeaders()
is less than 1
, no response headers were present.