Detect the Internet connection is offline?

后端 未结 19 1378
甜味超标
甜味超标 2020-11-22 00:53

How to detect the Internet connection is offline in JavaScript?

19条回答
  •  旧巷少年郎
    2020-11-22 01:40

    The problem of some methods like navigator.onLine is that they are not compatible with some browsers and mobile versions, an option that helped me a lot was to use the classic XMLHttpRequest method and also foresee the possible case that the file was stored in cache with response XMLHttpRequest.status is greater than 200 and less than 304.

    Here is my code:

     var xhr = new XMLHttpRequest();
     //index.php is in my web
     xhr.open('HEAD', 'index.php', true);
     xhr.send();
    
     xhr.addEventListener("readystatechange", processRequest, false);
    
     function processRequest(e) {
         if (xhr.readyState == 4) {
             //If you use a cache storage manager (service worker), it is likely that the
             //index.php file will be available even without internet, so do the following validation
             if (xhr.status >= 200 && xhr.status < 304) {
                 console.log('On line!');
             } else {
                 console.log('Offline :(');
             }
         }
    }
    

提交回复
热议问题