Thursday, September 4, 2008

Javascript code to check Network connection

Here is the javascript code to check if the network is connected. With the SetTimeout function in the code, the code would run automatically after every 500ms and check for the Network connection. This check would occur without a postback on the page - as it is client side code (javascript - actually more of AJAX). Better to place this code in a separate .js file instead of adding it in the aspx page. You do not need to add any special classes for this AJAX/Javascript code.

function CheckConn()
{
var requestUrl = "https://xyz.com/dev/WhosHere.aspx"

try //CreateXmlHttp() gives an error when there is no network
{
CreateXmlHttp();
if(XmlHttp)
{
XmlHttp.open("GET", requestUrl, false);
XmlHttp.send(null);

if (XmlHttp.status == '200')
{
//When Network connected : Status is 200
}
else
{
//Display error - no need for this ELSE loop though, as the TRY block would catch the error if network is disconnected
}
}
setTimeout('CheckConn()',5*100);
catch(e)
{
//Write the error which should show on network disconnect here instead.
}
setTimeout('CheckConn()',5*100);
}

No comments:

About Us