DEV Community

loading...

How to detect internet connection in html page with javascript -of cource

raghav9official profile image Raghav Yadav ・1 min read

Detecting the user's state of being online or offline is very important for a progressive web app to develop it tells the if a person is online or offline without importing any file and in a less time period.

The question is how do we detect that?

Well like always you can include a cdn:

<script src="https://netopa.github.io/hash.js/hashtag_1.0.1.js"></script>
Enter fullscreen mode Exit fullscreen mode

And return true or false with a simple code:

hash().isOnline(); //returns true or false
Enter fullscreen mode Exit fullscreen mode

And there are many other things you can do with this library to which I have mentioned in my previous article

OR going the other way:
Well navigator can help in this stage:

if(navigator.onLine){
  //online
}else{
  //offline
}
Enter fullscreen mode Exit fullscreen mode

That's all and make sure to hit the like if you liked the article and gift yourself a coffee from me ;)

Discussion (4)

Collapse
rajeshkumaryadavdotcom profile image
RajeshKumarYadav.com
if (window.navigator.onLine) {
  // Is connected to internet
} else {
  // Not connected to internet
}
Enter fullscreen mode Exit fullscreen mode

also looks good :)

Collapse
raghav9official profile image
Raghav Yadav Author

And yes this is also right but code should be minimal though

Collapse
kalashin1 profile image
Kinanee Samson

Thanks for sharing, i was looking for this

Collapse
raghav9official profile image
Raghav Yadav Author

Happy to help

Forem Open with the Forem app