34

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 application and I want to show a version if the user is offline and another version if the user is online.

For the moment i'm using this code :

if (navigator.onLine) {
    alert('online');
} else {
    alert('offline');
}

But this is working very slow to detect. sometimes it's just connected to a network without internet, it takes 5 to 10 seconds to alert false (No internet).

I took a look at Offline.js library, but I'm not sure if this library is useful in my case. and I don't know how to use it

7
  • 2
    Could you define very slow to detect? Commented Apr 22, 2015 at 15:38
  • 2
    possible duplicate of Detect that the Internet connection is offline?
    – jmoerdyk
    Commented Apr 22, 2015 at 15:39
  • 1
    @jmoerdyk to be fair, that post is 7 years old and technology has moved on leaps and bounds since then, not only that it looks as though the OP got their code from the answer by Edmhs on there. Commented Apr 22, 2015 at 15:43
  • That's right @JamieBarker I believe there is many ways on how to make that happens effectively. Commented Apr 22, 2015 at 15:46
  • 1
    Please, improve your question being more specific of what you want. Why do you think Offline.js isn't useful on your case? Commented Apr 30, 2015 at 13:28

11 Answers 11

16

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.

14
  • 2
    Mozilla Documentation: "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." developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine that won't effectively detect the Internet being down, but rather your LAN being down.
    – dmeglio
    Commented Apr 22, 2015 at 15:56
  • Thank you so much for your response, I have already tried that, this doesn't work on page load ! it works only on internet state change Commented Apr 22, 2015 at 15:58
  • @Jamie Barker, because I was calling out that said article indicates it doesn't meet the OP's requirements. Hence the answer is incorrect. He even said it himself "sometimes it's just connected to a network without internet" :)
    – dmeglio
    Commented Apr 22, 2015 at 16:00
  • @dman2306. You've quoted out of context. Let's take the whole sentence instead of half of it: "sometimes it's just connected to a network without internet, it takes 5 to 10 seconds to alert "false" (No internet)". So it's alerting false when connected to a network without internet. This is correct. The OP's problem is the fact it's taking 5-10 seconds to compute the answer. I'm not saying my answer is correct, just that your understanding of the issue doesn't tie in with what the question states. Commented Apr 22, 2015 at 16:08
  • @Stranger90 The first function is a "as soon as the page is loaded" function, however I'm guessing you've tried it and it doesn't help? Commented Apr 22, 2015 at 16:27
9
+25

i think you should try OFFLINE.js.. it looks pretty easy to use, just give it a try.

it even provides the option checkOnLoad which checks the connection immediately on page load.

Offline.check(): Check the current status of the connection.

Offline.state: The current state of the connection 'up' or 'down'

haven't tried it, would be nice to know if it works as intended.

EDIT took a little peak into the code, it uses the method with FAILED XHR REQUEST suggested in THIS SO Question

1
  • This project isn't actively maintained.
    – themefield
    Commented Mar 21, 2018 at 17:08
4

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.

4
  • 1
    Who says this is faster than navigator.onLine?
    – putvande
    Commented Apr 22, 2015 at 15:39
  • I took a look at that, that doesn't help a lot Commented Apr 22, 2015 at 15:40
  • 6
    @putvande It is more accurate, it checks for an INTERNET connection, not a NETWORK connection. From Mozilla docs: "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 if I'm on my LAN, but the Internet connection is dead, navigator.onLine returns true. The sample answer would say false.
    – dmeglio
    Commented Apr 22, 2015 at 15:56
  • 1
    @Stranger90 Why doesn't that help?
    – falsarella
    Commented Apr 29, 2015 at 0:20
3

navigator.onLine is a property that maintains a true/false value (true for online, false for offline). This property is updated whenever the user switches into "Offline Mode".

window.addEventListener('load', function() {

  function updateOnlineStatus(event) {
     document.body.setAttribute("data-online", navigator.onLine);
  }
  updateOnlineStatus();
  window.addEventListener('online',  updateOnlineStatus);
  window.addEventListener('offline', updateOnlineStatus);
});
3
// check if online/offline
// http://www.kirupa.com/html5/check_if_internet_connection_exists_in_javascript.htm
function doesConnectionExist() {
    var xhr = new XMLHttpRequest();
    var file = "http://www.yoursite.com/somefile.png";
    var randomNum = Math.round(Math.random() * 10000);

    xhr.open('HEAD', file + "?rand=" + randomNum, false);

    try {
        xhr.send();

        if (xhr.status >= 200 && xhr.status < 304) {
            return true;
        } else {
            return false;
        }
    } catch (e) {
        return false;
    }
}
1
  • Awesome but can be faster! Commented Aug 7, 2022 at 11:44
3

My solution is to grab a very small image (1x1), not cached and always onLine.

<head>
<script src="jquery.min.js"></script>
</head>
<body>
<script>
$( document ).ready(function() {
function onLine() {
alert("onLine")
}
function offLine() {
alert("offLine")
}
var i = new Image();
i.onload = onLine;
i.onerror = offLine;
i.src = 'http://www.google-analytics.com/__utm.gif';
});
</script>
<body>

Notes:

  • Use a local copy of jQuery otherwise it won't work offLine.

  • I've tested the code onLine/offLine and it works without delay.

  • Works with all browsers, Desktop or Mobile.

  • In case you wonder, there's no tracking made from Google Analytics as we don't use any arguments.

  • Feel free to change the image, just make sure it doesn't get cached and it's small in size.

2

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")
  }
});

1

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

1

You can use the new Fetch API which will trigger an error almost immediately if no network is present.

The problem with this is that the Fetch API has infant support at the moment (currently Chrome has the most stable implementation, Firefox and Opera is getting there, IE does not support it). There exists a polyfill to support the fetch principle but not necessarily the rapid return as with a pure implementation. On the other hand, an offline app would require a modern browser...

An example which will try to load a plain text file over HTTPS to avoid CORS requirements (link is picked at random, you should set up a server with a tiny text file to test against - test in Chrome, for now):

fetch("https://link.to/some/testfile")
    .then(function(response) {
        if (response.status !== 200) {  // add more checks here, ie. 30x etc.
            alert("Not available");     // could be server errors
        }
        else
            alert("OK");
    })
    .catch(function(err) {
        alert("No network");           // likely network errors (incl. no connection)
    });

Another option is to set up a Service worker and use fetch from there. This way you could serve an optional/custom offline page or a cached page when the requested page is not available. Also this is a very fresh API.

0

best one liner

console.log(navigator.onLine ? 'online' : 'offline');

Not the answer you're looking for? Browse other questions tagged or ask your own question.