Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check internet connection in Android WebView (Cordova)

Tags:

I know there is a lot of questions and answers about this in Stackoverflow, I read a lot of them, but none of them work.

I clarified in the title Android WebView because it is the most important target, but I would like this works in other devices too. I tested the following code on a app built with Intel XDK installed on a SM-G355M with Android 4.4.2 and on Safari installed on an iPhone 5C with iOS 9.3.4;

All I get in both cases is the same value, true (sometimes I get false even I have an internet connection).

I tried:

  1. navigator.onLine, it gives always the same value.
  2. document.addEventListener("online", ... doesn't trigger
  3. ajax doesn't work, anyway doesn't affect to the server?

Code: https://nanilab.com/stackoverflow/webview-internet-connection.php(This link is now broken)


Option 1:

function option1(){
    var isOffline = 'onLine' in navigator && !navigator.onLine,
        text = isOffline == true ? ' without connection ' : ' connected ';

    $('.option-one span').text(text);
    $('.option-one i').text('checked').hide().fadeIn(200);

    setTimeout(function(){
        option1();
    }, 1000);
}

Option 2:

window.addEventListener("offline", function(){ $('.option-two span').text(' without connection'); }, false);
window.addEventListener("online", function(){ $('.option-two span').text(' connected'); }, false);

Option 3:

function option3(){
    $.ajax({
        url: '/stackoverflow/blank.php',
        success: function(data){
            print(' connected ');
        },
        error: function(jqXHR, textStatus, error) {
            print(' without connection ');
        }
    }); 

    function print(text){
        $('.option-three span').text(text);
        $('.option-three i').text('checked').hide().fadeIn(200);

        setTimeout(function(){
            option3();
        }, 2000);
    }
}

app built with Intel XDK installed on a SM-G355M with Android 4.4.2

https://youtu.be/wHJHG5dP_eM


What I am doing wrong?