In this tutorial, We will see how to detect internet connection using javascript. This is a pretty simple code to check the internet connection active or not.
Why we use this method: Most of the website uses this method to improve better user experience, If you check for the big website like Netflix, Quora and Google, they are using the same method to show the warning message of No internet connection.
- For the better user experience
- Let user stay on your site
- Increase user communication with your page
Syntax to check internet connection is active or not using javascript
<button onclick="fn_checkInternet()">
Click Here to Check
</button>
// Javascript Code
<script>
function fn_checkInternet()
{
if (navigator.onLine)
{
alert('Online');
}
else
{
alert('Offline');
}
}
window.addEventListener('online', function (e)
{
alert('You Are Back Online');
}, false);
window.addEventListener('offline', function (e)
{
alert('You went offline');
}, false);
</script>
Explanation of Syntax
function fn_checkInternet()
{
if (navigator.onLine)
{
alert('Online');
}
else
{
alert('Offline');
}
}
2. Check if suddenly the user's connection is down.
window.addEventListener('offline', function (e)
{
alert('You went offline');
}, false);
3. Check if user back online or internet started working.
window.addEventListener('online', function (e)
{
alert('You Are Back Online');
}, false);
Post a Comment