Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 399
Stranger B. Avatar asked Apr 22 '15 15:04

Stranger B.


2 Answers

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.

like image 142
Jamie Barker Avatar answered Oct 08 '22 11:10

Jamie Barker


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

like image 43
Doml The-Bread Avatar answered Oct 08 '22 13:10

Doml The-Bread