Detect the Internet connection is offline?

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

How to detect the Internet connection is offline in JavaScript?

相关标签:
19条回答
  • 2020-11-22 01:41

    My way.

    <!-- the file named "tt.jpg" should exist in the same directory -->
    
    <script>
    function testConnection(callBack)
    {
        document.getElementsByTagName('body')[0].innerHTML +=
            '<img id="testImage" style="display: none;" ' +
            'src="tt.jpg?' + Math.random() + '" ' +
            'onerror="testConnectionCallback(false);" ' +
            'onload="testConnectionCallback(true);">';
    
        testConnectionCallback = function(result){
            callBack(result);
    
            var element = document.getElementById('testImage');
            element.parentNode.removeChild(element);
        }    
    }
    </script>
    
    <!-- usage example -->
    
    <script>
    function myCallBack(result)
    {
        alert(result);
    }
    </script>
    
    <a href=# onclick=testConnection(myCallBack);>Am I online?</a>
    
    0 讨论(0)
  • 2020-11-22 01:41

    request head in request error

    $.ajax({
        url: /your_url,
        type: "POST or GET",
        data: your_data,
        success: function(result){
          //do stuff
        },
        error: function(xhr, status, error) {
    
          //detect if user is online and avoid the use of async
            $.ajax({
                type: "HEAD",
                url: document.location.pathname,
                error: function() { 
                  //user is offline, do stuff
                  console.log("you are offline"); 
                  }
             });
        }   
    });
    
    0 讨论(0)
  • 2020-11-22 01:42

    There are a number of ways to do this:

    • AJAX request to your own website. If that request fails, there's a good chance it's the connection at fault. The JQuery documentation has a section on handling failed AJAX requests. Beware of the Same Origin Policy when doing this, which may stop you from accessing sites outside your domain.
    • You could put an onerror in an img, like <img src="http://www.example.com/singlepixel.gif" onerror="alert('Connection dead');" />.

    This method could also fail if the source image is moved / renamed, and would generally be an inferior choice to the ajax option.

    So there are several different ways to try and detect this, none perfect, but in the absence of the ability to jump out of the browser sandbox and access the user's net connection status directly, they seem to be the best options.

    0 讨论(0)
  • 2020-11-22 01:46

    There are 2 answers forthis for two different senarios:-

    1. If you are using JavaScript on a website(i.e; or any front-end part) The simplest way to do it is:

      <h2>The Navigator Object</h2>
      
      <p>The onLine property returns true if the browser is online:</p>
      
      <p id="demo"></p>
      
      <script>
        document.getElementById("demo").innerHTML = "navigator.onLine is " + navigator.onLine;
      </script>
      

    2. But if you're using js on server side(i.e; node etc.), You can determine that the connection is lost by making failed XHR requests.

      The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully.

    0 讨论(0)
  • 2020-11-22 01:48
    window.navigator.onLine
    

    is what you looking for, but few things here to add, first, if it's something on your app which you want to keep checking (like to see if the user suddenly go offline, which correct in this case most of the time, then you need to listen to change also), for that you add event listener to window to detect any change, for checking if the user goes offline, you can do:

    window.addEventListener("offline", 
      ()=> console.log("No Internet")
    );
    

    and for checking if online:

    window.addEventListener("online", 
      ()=> console.log("Connected Internet")
    );
    
    0 讨论(0)
  • 2020-11-22 01:50

    You can use $.ajax()'s error callback, which fires if the request fails. If textStatus equals the string "timeout" it probably means connection is broken:

    function (XMLHttpRequest, textStatus, errorThrown) {
      // typically only one of textStatus or errorThrown 
      // will have info
      this; // the options for this ajax request
    }
    

    From the doc:

    Error: A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror". This is an Ajax Event

    So for example:

     $.ajax({
       type: "GET",
       url: "keepalive.php",
       success: function(msg){
         alert("Connection active!")
       },
       error: function(XMLHttpRequest, textStatus, errorThrown) {
           if(textStatus == 'timeout') {
               alert('Connection seems dead!');
           }
       }
     });
    
    0 讨论(0)
提交回复
热议问题