2013-01-11 1 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.

전술 한 바와 같이,이 속성의 trustable되지 않으므로, 제 생각에 가장 좋은 해결 방법은 서버 측 페이지로 아약스 호출입니다. 브라우저가 오프라인이면 연결이 실패하고 onerror 이벤트가 호출됩니다. 그렇지 않은 경우 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 코드를 실행하려면 어떻게해야합니까? –

관련 문제