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

前端 未结 10 1731
你的背包
你的背包 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:39

    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.

提交回复
热议问题