-1

I need a script to check if the browser is online or not.

navigator.onLine doesn't really tell you if the browser is online, it just tells you if there's a network.

I've seen some plugins like:

https://github.com/sindresorhus/is-online

By I need to do it without installing third party plugins.

I see that the above plugin uses this URL:

http://captive.apple.com/hotspot-detect.html

Which returns "success" if you're online.

How can I do this without installing and plugins?

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
  • 2
    request a resource online and if it comes back, than you have internet. – epascarello Sep 12 '18 at 19:35
  • 1
    Possible duplicate of [Check if Internet Connection Exists with Javascript?](https://stackoverflow.com/questions/2384167/check-if-internet-connection-exists-with-javascript) – Bonnie Sep 12 '18 at 19:35
  • It's a few dozen lines of JS; even if you didn't just check a request for success/failure, I bet you could duplicate the functionality you need. – Dave Newton Sep 12 '18 at 19:36
  • another possible duplicate with a good solution: https://stackoverflow.com/questions/20043215/check-internet-connectivity-with-jquery – Sigma Sep 12 '18 at 19:36

1 Answers1

0

Set the following code inside an interval and get your own online checker.

let online = 0;
$.ajax({
    type: "GET",
    url: "/path/to/page/in/internet/or/in/your/site",
    success: function (msg) {
        online = 1;
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        online = -1;
    }
});
Coral Kashri
  • 3,436
  • 2
  • 10
  • 22
  • Better to suggest a callback/etc. instead of relying on a global, which would lead to a need to poll, timeout, etc. But it's a dupe question anyway. – Dave Newton Sep 12 '18 at 19:49