How to programmatically check internet connection availability using jquery

I am developing an Android phonegap application. When I launch the application without an Internet connection, it is forcibly closed. I need to check internet connection in dom before calling ajax using jquery / javascript

Here is my sample code:

var a=navigator.onLine; if(a){ alert('online'); $.ajax({ type: "GET", url: url, dataType: 'json', async: true, cache: false, success: function(data){ alert('success'); }, error: function(e){ alert('error'); } }); }else{ alert('ofline'); } 

But I always get a warning ("online"), even if there is no internet connection. Please kindly guide me. Thanks at Advance

+4
source share
2 answers

As you indicated in the tag, you cannot access the specifications of the equipment without the PhoneGap API , and to check the available connection all you need is to implement Connection

The connection object provides access to information about a cellular cellular device and Wi-Fi.

 function checkConnection() { var networkState = navigator.network.connection.type; var states = {}; states[Connection.UNKNOWN] = 'Unknown connection'; states[Connection.ETHERNET] = 'Ethernet connection'; states[Connection.WIFI] = 'WiFi connection'; states[Connection.CELL_2G] = 'Cell 2G connection'; states[Connection.CELL_3G] = 'Cell 3G connection'; states[Connection.CELL_4G] = 'Cell 4G connection'; states[Connection.NONE] = 'No network connection'; alert('Connection type: ' + states[networkState]); } checkConnection(); 

Full example available in PhoneGap Docs

+8
source

Perhaps you can use the deviceโ€™s network connection status property:

 var a = (navigator.network.connection.type != Connection.NONE); 

Also see the "Connection" API

+2
source

Source: https://habr.com/ru/post/1398763/


All Articles