Check Internet connectivity with jquery

前端 未结 7 696
无人及你
无人及你 2020-12-05 20:29

I am trying to check for the internet connection by sending a GET request to the server. I am a beginner in jquery and javascript. I am not using navigator.onLine

相关标签:
7条回答
  • 2020-12-05 21:03

    $.get() returns a jqXHR object, which is promise compatible - therefore no need to create your own $.Deferred.

    var check_connectivity = {
        ...
        is_internet_connected: function() {
            return $.get({
                url: "/app/check_connectivity/",
                dataType: 'text',
                cache: false
            });
        },
        ...
    };
    

    Then :

    check_connectivity.is_internet_connected().done(function() {
        //The resource is accessible - you are **probably** online.
    }).fail(function(jqXHR, textStatus, errorThrown) {
        //Something went wrong. Test textStatus/errorThrown to find out what. You may be offline.
    });
    

    As you can see, it's not possible to be definitive about whether you are online or offline. All javascript/jQuery knows is whether a resource was successfully accessed or not.

    In general, it is more useful to know whether a resource was successfully accessed (and that the response was cool) than to know about your online status per se. Every ajax call can (and should) have its own .done() and .fail() branches, allowing appropriate action to be taken whatever the outcome of the request.

    0 讨论(0)
  • 2020-12-05 21:04

    This piece of code will continue monitoring internet connection click bellow "Run code snippet" button and see it in action.

    function checkInternetConnection(){
            var status = navigator.onLine;
            if (status) {
                console.log('Internet Available !!');
            } else {
                console.log('No internet Available !!');
            }  
            setTimeout(function() {
                checkInternetConnection();
            }, 1000);
          }
    
    //calling above function
    checkInternetConnection();

    0 讨论(0)
  • 2020-12-05 21:07

    Do you mean to check the internet connection if it's connected?

    If so, try this:

    $.ajax({
        url: "url.php",
        timeout: 10000,
        error: function(jqXHR) { 
            if(jqXHR.status==0) {
                alert(" fail to connect, please check your connection settings");
            }
        },
        success: function() {
            alert(" your connection is alright!");
        }
    });
    
    0 讨论(0)
  • 2020-12-05 21:16
    try this 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>
     if (! window.jQuery) {
     alert('No internet Connection !!');
      }
     else {
     // internet connected
     }
    

    Jquery Plugin for Detecting Internet Connection

    0 讨论(0)
  • 2020-12-05 21:20

    you cannot get simple true or false in return, give them a callback handler

    function is_internet_connected(callbackhandler)
    {
    $.get({
      url: "/app/check_connectivity/",
      success: function(){
         callbackhandler(true);
      },
      error: function(){
         callbackhandler(false);
      },
      dataType: 'text'
    });
    }
    
    0 讨论(0)
  • 2020-12-05 21:20

    I just use the navigator onLine property, according to W3C http://www.w3schools.com/jsref/prop_nav_online.asp

    BUT navigator only tells us if the browser has internet capability (connected to router, 3G or such). So if this returns false you are probably offline but if it returns true you can still be offline if the network is down or really slow. This is the time to check for an XHR request.

    setInterval(setOnlineStatus(navigator.onLine), 10000);
    
    function setOnlineStatus(online)
    {
        if (online) {
        //Check host reachable only if connected to Router/Wifi/3G...etc
            if (hostReachable())
                $('#onlineStatus').html('ONLINE').removeAttr('class').addClass('online');
            else
                $('#onlineStatus').html('OFFLINE').removeAttr('class').addClass('offline');
        } else {
            $('#onlineStatus').html('OFFLINE').removeAttr('class').addClass('offline');
        }
    }
    
    function hostReachable()
    {
        // Handle IE and more capable browsers
        var xhr = new (window.ActiveXObject || XMLHttpRequest)("Microsoft.XMLHTTP");
        var status;
    
        // Open new request as a HEAD to the root hostname with a random param to bust the cache
        xhr.open("HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);
    
        // Issue request and handle response
        try {
            xhr.send();
            return (xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304));
        } catch (error) {
            return false;
        }
    
    }
    

    EDIT: Use port number if it is different than 80, otherwise it fails.

    xhr.open("HEAD", "//" + window.location.hostname + ":" + window.location.port + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false);
    
    0 讨论(0)
提交回复
热议问题