How to check if the user is online using javascript or any library?

前端 未结 10 1684
你的背包
你的背包 2020-12-03 01:35

I need some help on how I could check the internet connection using Javascript or jQuery or any library if available. cause i\'m developing an offline appl

相关标签:
10条回答
  • 2020-12-03 01:56

    I just got this bit of code functionality from a Mozilla Site:

    window.addEventListener('load', function(e) {
      if (navigator.onLine) {
        console.log('We\'re online!');
      } else {
        console.log('We\'re offline...');
      }
    }, false);
    
    window.addEventListener('online', function(e) {
      console.log('And we\'re back :).');
    }, false);
    
    window.addEventListener('offline', function(e) {
      console.log('Connection is down.');
    }, false);
    

    They even have a link to see it working. I tried it in IE, Firefox and Chrome. Chrome appeared the slowest but it was only about half a second.

    0 讨论(0)
  • 2020-12-03 01:58

    You can use SignalR, if you're developing using MS web technologies. SignalR will establish either long polling or web sockets depending on your server/client browser technology, transparent to you the developer. You don't need to use it for anything else than determining if you have an active connection to the site or not.

    If SignalR disconnects for any reason, then you have lost connection to the site, as long as your SignalR server instance is actually installed on the site. Thus, you can use $.connection.hub.disconnected() event/method on the client to set a global var which holds your connection status.

    Read up about SignalR and how to use it for determining connection states here... http://www.asp.net/signalr/overview/guide-to-the-api/handling-connection-lifetime-events#clientdisconnect

    0 讨论(0)
  • 2020-12-03 02:00

    Take a look at Detect that the Internet connection is offline? Basically, make an ajax request to something you know is likely to be up (say google.com) and if it fails, there is no internet connection.

    0 讨论(0)
  • 2020-12-03 02:00

    Try utilizing WebRTC , see diafygi/webrtc-ips; in part

    Additionally, these STUN requests are made outside of the normal XMLHttpRequest procedure, so they are not visible in the developer console or able to be blocked by plugins such as AdBlockPlus or Ghostery. This makes these types of requests available for online tracking if an advertiser sets up a STUN server with a wildcard domain.


    modified minimally to log "online" or "offline" at console

    // https://github.com/diafygi/webrtc-ips
    function online(callback){
    
        //compatibility for firefox and chrome
        var RTCPeerConnection = window.RTCPeerConnection
            || window.mozRTCPeerConnection
            || window.webkitRTCPeerConnection;
        var useWebKit = !!window.webkitRTCPeerConnection;
    
        //bypass naive webrtc blocking using an iframe
        if(!RTCPeerConnection) {
            //NOTE: you need to have an iframe in the page
            // right above the script tag
            //
            //<iframe id="iframe" sandbox="allow-same-origin" style="display: none"></iframe>
            //<script>...getIPs called in here...
            //
            var win = iframe.contentWindow;
            RTCPeerConnection = win.RTCPeerConnection
                || win.mozRTCPeerConnection
                || win.webkitRTCPeerConnection;
            useWebKit = !!win.webkitRTCPeerConnection;
        }
    
        //minimal requirements for data connection
        var mediaConstraints = {
            optional: [{RtpDataChannels: true}]
        };
    
        //firefox already has a default stun server in about:config
        //    media.peerconnection.default_iceservers =
        //    [{"url": "stun:stun.services.mozilla.com"}]
        var servers = undefined;
    
        //add same stun server for chrome
        if(useWebKit)
            servers = {iceServers: [{urls: "stun:stun.services.mozilla.com"}]};
    
        //construct a new RTCPeerConnection
        var pc = new RTCPeerConnection(servers, mediaConstraints);
    
        //create a bogus data channel
        pc.createDataChannel("");
    
        var fn = function() {};
    
        //create an offer sdp
        pc.createOffer(function(result){
    
            //trigger the stun server request
            pc.setLocalDescription(result, fn, fn);
    
        }, fn);
    
        //wait for a while to let everything done
        setTimeout(function(){
            //read candidate info from local description
            var lines = pc.localDescription.sdp.split("\n");
            // return `true`:"online" , or `false`:"offline"
            var res = lines.some(function(line) {
              return line.indexOf("a=candidate") === 0
            });
            callback(res);
        }, 500);
    }
    
    //Test: Print "online" or "offline" into the console
    online(function(connection) {
      if (connection) {
        console.log("online")
      } else {
        console.log("offline")
      }
    });

    0 讨论(0)
提交回复
热议问题