-1

I am using this cordova-plugin-network-information plugin with below code.

<script type="text/javascript" charset="utf-8">

    // Wait for device API libraries to load
    //
    document.addEventListener("deviceready", onDeviceReady, false);

    // device APIs are available
    //
    function onDeviceReady() {
        checkConnection();
    }

    function checkConnection() {
        var networkState = navigator.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.CELL]     = 'Cell generic connection';
        states[Connection.NONE]     = 'No network connection';

        if(networkState != Connection.NONE){
            window.location.href = "index2.html";
        } else{
            document.getElementById('custom-message').style.display = "block";
        }

    }

    </script>

This plugin working fine but it redirects to 2nd page (index2).

I want to in a such way that first it checks the connection & then load the same page index page (no need to create index2 page) And if fails (No Internet) then throw the custom error message.

Thanks

A2zbollywood
  • 35
  • 1
  • 8

1 Answers1

0

I'm using this:

function init() {
    document.addEventListener("online", onOnline, false);
    document.addEventListener("offline", onOffline, false);
    document.addEventListener('deviceready', startUp, false);
    document.addEventListener("backbutton", onBackKeyDown, false);
}
function onOnline() { 
    $('#noInternet').hide();
}
function onOffline() { 
    $('#noInternet').show();
}

It not only checks the status on pageload, but also when it changes. So if the connection goes offline a custom error message (#noInternet) shows. When the connection goes back online, the message disappears.

Apart from my code, to make your code functional change this:

if(networkState != Connection.NONE){

To:

if(states[networkState] != states[Connection.NONE]){
GreyRoofPigeon
  • 17,833
  • 4
  • 36
  • 59