Reputation: 239
What is the best way to check if a site is up and running or down with JavaScript?
Upvotes: 12
Views: 39693
Reputation: 126
Based on Spliffster's comment:
This code will based on the browser timeout try to reach a specific IP until it is available asynchronously. You may want to add code to prevent it from trying to long.
<head>
<script>
function check_available(ip){
var el=document.getElementById("check_pic");
el.src="https://"+ip+"/images/powered_by.gif?now="+Math.random();
}
function check_success(url){
alert("redirect now :) - url:"+url);
}
</script>
</head>
<body>
<img style="visibility:hidden" id='check_pic' src="/images/powered_by.gif" onabort="alert('interrupted')" onload="check_success('http://10.0.0.1/redirect/me/here')" onerror="check_available('10.17.71.150')"/>
</body>
[Edit]
Sidenote: xmlhttprequest will not work as the browser will throw a cross origin exception. This mozilla.dev link gives more background infos and shows examples using access control header response statements. Be aware that the access control header field is serverside (the site that is being probed) and you might not be able to control that field (not enabled by default).
timing issues There are differences in timing when using xmlhttprequests for cross origin calls. Since the browser must wait for the response to evaluate possible access control header fields, a call to a non existent website will run into the browsers request timeout. A call to an existing website will not run into this timeout and error out earlier with a cross origin exception (only visible in the browser, javascript never gehts this info!). So there's also the possibility to measure the time from xmlhttprequest.send() to first response (in callback). An early callback call will indicate that the website is up from the browsers point of view but at least with xmlhttprequest you wont be able to evaluate the returncode (since this is blocked bei cross origin policy).
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
//stopwatch.stop and calc timediff. timediff < default browser request timeout indicates website is up from this browsers point of view. No clues on request status or anything else, just availability
}
self.xmlHttpReq.send(null);
//stopwatch.start
Upvotes: 11
Reputation: 7219
No AJAX required, just plant an image from the remote site hidden into your site and monitor the load HTTP response status of this image. This might need some tweaks for true crossbrowser compatibility.
<script type="text/javascript">
function set_test(name,status){
var el=document.getElementById(name+'_test');
el.innerHTML=status?'Yes, you are logged in':'No, you\'re not logged in';
el.style.color=status?'#0a0':'#a00';
el.style.fontWeight='bold';
}
(function(){
var gmail_test=document.getElementById('gmail_test');
gmail_test.innerHTML='Checking...';
var img=document.createElement('img');
img.src='//mail.google.com/mail/photos/static/AD34hIhNx1pdsCxEpo6LavSR8dYSmSi0KTM1pGxAjRio47pofmE9RH7bxPwelO8tlvpX3sbYkNfXT7HDAZJM_uf5qU2cvDJzlAWxu7-jaBPbDXAjVL8YGpI?rand='+Math.random();
img.onload=function(){set_test('gmail',1)};
img.onerror=function(){set_test('gmail',0)};
img.style.display='none';
document.body.appendChild(img);
})();
</script>
Upvotes: 9
Reputation: 1107
Ajax alone might not be the answer - if you're trying to check a remote server, since by default you can't access a remote server via ajax.
You can however access the server that the script resides/lives on - which means you can create some kind of script that acts as a proxy e.g. server side script that checks if the site in question is active and call that script via your ajax call.
An example (PHP/C# & VB.Net) of how to do this: http://www.cstruter.com/articles/article/2/8
As for Checking the status of the server:
C#
string URL = "http://www.stackoverflow.com";
WebRequest request = WebRequest.Create(URL);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//if (response.StatusCode == HttpStatusCode.something
PHP
@$headers = get_headers($url);
return (preg_match('/^HTTP\/\d.\d\s+(200|301|302)/', $headers[0]));
Upvotes: 1
Reputation: 251232
That's quite difficult to do with JavaScript as you will encounter cross-site scripting problems.
It is much easier to do with a server-side language as you can attempt to load any web page.
At the very least, you will most likely need to implement a server-side proxy to get the remote page for you. There are lots of examples for this - let me know what language you can use server side and I can find you an example.
Upvotes: 3
Reputation: 7482
Make a get ajax call and examine the output.
Or, make a get ajax call to isitup.org and examine the output
Upvotes: 3