How to detect device internet connection in jQuery Mobile

I am creating this simple mobile polling webpage using HTML5, CSS3, jQuery Mobile, jQuery UI, ASP.NET, C # and some jQuery plugins. One of the requirements is to display a popup / dialog box (javascript warning or jQuery dialog for mobile devices, or much better if it is a jQuery UI dialog), which will notify the user when the Internet connection is not connected to the device (in particular, Android ) I currently have this code:

<link rel="stylesheet" href="../Scripts/jqueryui/jquery-ui.css" type="text/css" media="all" /> <link rel="stylesheet" href="../Scripts/jquery.mobile-1.1.0.css" /> <script src="../Scripts/jquery-1.7.1.js" type="text/javascript"></script> <script src="../Scripts/jquery.mobile-1.1.0.js" type="text/javascript"></script> <script src="../Scripts/jqueryui/jquery.min.js" type="text/javascript"></script> <script src="../Scripts/jqueryui/jquery-ui.min.js" type="text/javascript"></script> <script src="../Scripts/jquery.validate.js" type="text/javascript"></script> <script type="text/javascript"> var online = window.navigator.onLine; if (!online) { alert('Please check your internet connection and try again.'); } function checkInternet() { var online = window.navigator.onLine; if (!online) { alert('Please check your internet connection and try again.'); } } </script> 

then I put the JavaScript function in the onsubmit event form:

 <form id="frmSurvey" runat="server" class="validate" onsubmit="checkInternet()"> 

It works when I view it on a browser on my desktop / PC, but it doesn’t work on a mobile device at all. The jQuery Mobile error download page.

Since this is not a requirement that I changed, the jQuery Mobile file commented out part of the page load error message and it no longer appears. I tried Google a lot to search for any related topics, but could not find.

It’s really hard for me to make this possible. Please help me guys!

Thanks in advance!

+7
source share
1 answer

There are several solutions that will allow you to meet your needs.

Solution 1

This solution requires jQuery, and since you are using jQuery Mobile, it will work like a charm.

 $.ajaxSetup({ timeout: 1, // Microseconds, for the laughs. Guaranteed timeout. error: function(request, status, maybe_an_exception_object) { if(status == 'timeout') alert("Internet connection is down!"); } }); 

For more information, see the official ajaxSetup documentation.

Decision 2

This is a bit complicated because it depends on the implementation of the HTML5 browser.

Basically you need to check if this value is true or false:

window.navigator.onLine - will be false if the user is disconnected.

Working example: http://jsfiddle.net/Gajotres/VXWGG/1/

Tested:

  • Windows firefox

  • Windows Google Chrome

  • Windows IE9 and IE10

  • Android 4.1.1 Chrome

  • iPad 3 Safari

  • iPad3 Chrome

+10
source

All Articles