2013-01-11 48 views
18

我遇到了Navigator.onLine属性的问题。navigator.onLine并不总是有效

我正在WAMP上运行的本地自助服务机上运行一个简单的网站。

在我的笔记本电脑上,当我测试这个工程。我关闭WiFi并显示警告框。在运行WAMP软件的自助服务终端上断开互联网不会产生错误状态。任何想法为什么?

var online = navigator.onLine; 

if (online == false) { 

    alert("Sorry, we currently do not have Internet access."); 
    location.reload(); 

} 

回答

35

MDN约navigator.onLine

In Chrome and Safari, if the browser is not able to connect to a local area network (LAN) or a router, it is offline; all other conditions return true. So while you can assume that the browser is offline when it returns a false value, you cannot assume that a true value necessarily means that the browser can access the internet.

如上所述,这个属性是不可信的,所以,在我看来,最好的解决方法是一个AJAX调用服务器端页面。如果浏览器处于脱机状态,则连接将失败,因此将调用该事件。否则,onload事件被称为:

function isOnline(no,yes){ 
    var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp'); 
    xhr.onload = function(){ 
     if(yes instanceof Function){ 
      yes(); 
     } 
    } 
    xhr.onerror = function(){ 
     if(no instanceof Function){ 
      no(); 
     } 
    } 
    xhr.open("GET","anypage.php",true); 
    xhr.send(); 
} 

isOnline(
    function(){ 
     alert("Sorry, we currently do not have Internet access."); 
    }, 
    function(){ 
     alert("Succesfully connected!"); 
    } 
); 
+0

感谢您的帮助,这指出我在正确的方向。 – Jako

+0

小修改 - 您的参数中的函数顺序被交换,应该是'function isOnline(yes,no){...}' – Johan

+0

如果我想从Google的CDN加载jQuery,并在请求成功时执行jQuery代码,该怎么办? –

相关问题