我要做的是检查互联网连接,如果无法连接,它会再试几次。我目前用来检查的代码位于https://gist.github.com/fryn/943537,因为它似乎是最有希望的(我对其他解决方案的运气不太好)。
我的问题是“serverReachable()”函数似乎总是返回 false,即使连接了互联网。有什么建议么?我愿意使用其他解决方案,这只是我迄今为止得到的最接近的解决方案。
谢谢!
这是我的代码:(所有警报都用于调试目的)
var attemptCount = 0;
function onOffLine(){
alert("start of onOffLine function");
var z = "N";
var connectionTest = serverReachable();
if(serverReachable()){
alert("found to have connection.");
document.getElementById("connected").style.visibility = "visible";
document.getElementById("notConnected").style.visibility = "hidden";
z = "yes";
alertMe(z);
}else if(connectionTest == false && attemptCount < 4){
document.getElementById("notConnected").style.visibility = "visible";
alert("No connection, recursing.." + attemptCount);
attemptCount++;
setTimeout("onOffLine()", 3000);
}else if(attemptCount == 4){
alert("all attempts failed.");
document.getElementById("notConnected").style.visibility = "visible";
z = "N";
alertMe(z);
}
}
function alertMe(z){
if(z == "N"){
alert("Browser is loaded;\nInternet not connected");
}else if(z == "Y"){
alert("Browser is open and ready");
}
}
function serverReachable() {
alert("serverReachable() called");
var x = new XMLHttpRequest;
x.open('HEAD', '/?' + +new Date, false);
try {
x.send();
var s = x.status;
return s >= 200 && s < 300 || s === 304;
} catch (e) {
return false;
}
}