Introduction
Today we will see how you can see if the user is connected to the network. Sometimes the user's connection is not stable, and you want to take action or show a warning. Please connect to the internet to use this feature. So this can be possible with the navigator.online property in javascript.
Navigator.online
navigator.online
is a property of the navigator
object in JavaScript that defines whether or not the user is currently connected to the network. It returns a boolean value if it's true the user is connected to the internet and false if it is not connected to the internet.
It only checks whether the browser is connected to the internet or not. It does not guarantee whether the internet connection is fast or reliable.
Example
var isOnline = navigator.onLine
if (isOnline) {
alert("Awesome! You are online");
} else {
alert("Please check your Internet Connectivity")
}
So here, if the user is connected to the internet, then it shows an alert message,
else this will popup below message,
Pro Tip - You can also add an event listener to detect changes in the online status.
Conclusion
So with this little piece of code, you can detect whether the user is connected to the internet or offline. I hope you understand this example and try to implement this further by doing some further code changes. Let me know some more examples of where we can use this property. Happy Coding :)