Tuesday, March 13, 2018

Check Internet Connection using JavaScript and HTML

Detect the Internet connection is offline, Detect Online Connection with JavaScript, Check If Internet Connection Exists in JavaScript, Check Internet Connection in HTML using JavaScript

Today, We are going to learn how to check internet connection using html and javascript. We have used pure javascript to check offline and online status of internet connection. Nowadays these two new events supported by most of the browser: "online" and "offline".These two events are fired on the <body> of each page when the browser switches between online and offline mode. Additionally, the events bubble up from document.body, to document, ending at window.

You can register listeners for these events by following below steps :
  1. Using addEventListener on the window, document, or document.body.
  2. By setting the online or offline properties on document or document.body to a JavaScript Function object.


Check internet connection

Lets see the complete example to check online and offline status of internet connection, using below javascript code.
check-internet-status.html
<html>
<head>
<script>
function updateOnlineStatus() {
    document.getElementById("status").innerHTML = "User is online";
}

function updateOfflineStatus() {
    document.getElementById("status").innerHTML = "User is offline";
}

window.addEventListener('online', updateOnlineStatus);
window.addEventListener('offline', updateOfflineStatus); 
 
</script> 
</head>
<body>
 <div id="status">User is online</div>
</body>
</html>


Additionally you can also use below javascript source code to check internet connection.
if(navigator.onLine)
  {
    alert('You are Online');
  }
  else
  {
    alert('You are Offline')
  }

Demo Link :
https://skptricks.github.io/learncoding/check-internet-connection-using-javascript/check-internet-status.html

This is all about checking internet connection through javascript. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

2 comments: