Question

I have to check for network connection on app start, but PhoneGap online/offline event fires after any state change to it. If the app starts in online mode, the online events doesn't fired, until it gets offline, then comes online.

This is the code,

initialize: function() {
    this.bindEvents();
},

bindEvents: function() {
    document.addEventListener('deviceready', this.onDeviceReady, false);
},

onDeviceReady: function() {        
    document.addEventListener("offline", this.onOffline, false);
    document.addEventListener("online", this.onOnline, false);
},

That's wrong with the code ?

Was it helpful?

Solution

The online/offline events are made to fire on state change only. If you need to check the connectivity at a certain point, you can use navigator.network.connection.type.

initialize: function() {
    this.bindEvents();
},

bindEvents: function() {
    document.addEventListener('deviceready', this.onDeviceReady, false);
},

onDeviceReady: function() {        
    document.addEventListener("offline", this.onOffline, false);
    document.addEventListener("online", this.onOnline, false);
    if((navigator.network.connection.type).toUpperCase() == "NONE" && 
       (navigator.network.connection.type).toUpperCase() == "UNKNOWN") {
        this.onOffline();
    }
    else {
        this.onOnline();
    }   
},

Hope this helps you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top