Check network connectivity using javascript

Check network connectivity using javascript

In Modern web application form validation and lots of business logic related with UI resides on client side which is nothing but our browsers. User registration is first step where customer enter personal and other detail based on type of application. Suppose while filling up the registration form network connectivity lost and user submitted the form. In that scenario registration fails and user has to re-fill the form and submit again.

The solution of this problem is that before submitting the user registration form, developer should check whether connection are available or not. If connectivity lost, developer should store data locally and submit the data once connections are available.

Below example demonstrate connectivity check using javascript.

	<title>Connectivity Example</title>
	<h2>Connectivity Example</h2>
	<p>Status : <label id="status"></label></p>

		function updateStatus() {
			var condition = navigator.onLine ? 'online' : 'offline';
			document.querySelector('#status').innerHTML = condition;

		window.addEventListener('online', updateStatus);
		window.addEventListener('offline', updateStatus);

		//init the page on load

navigator.onLine is javascript method which is associated with browser let us know the current status of network. In above example we have created updateStatus() method which update the label with current state. Also window events are added so to update the status in case availability of network and vice-versa.

1) When device connected with data network


2) When device doesn’t connected with data network


Leave a Reply

Your email address will not be published. Required fields are marked *