Alireza
Alireza

Reputation: 6868

Online/Offline events not firing in Cordova?

My Resume, Ready and Paused events work just fine. I have problem with online/offline events. When I put my device in Airplane mode and vice verse nothing happens. When I disconnect from Internet I don't get any result. This is My code:

var app ={

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

bindEvents:function(){
    document.addEventListener("deviceready", this.onDeviceReady,false);
    document.addEventListener("pause", this.onPause,false);
    document.addEventListener("resume", this.onResume,false);
},

onDeviceReady:function() {
    document.addEventListener("online", this.onOnline,false);
    document.addEventListener("offline", this.onOffline,false);
    console.log("Readyii");
    app.testzone = document.getElementById("test-zone");
    app.testzone.innerHTML = "Readyii";
},

onPause: function() {
    app.testzone.innerHTML += "<br />Paused";
},

onResume: function() {
    app.testzone.innerHTML += "<br />Resumed";
},

onOnline: function() {
    app.testzone.innerHTML += "<br />Online";
},

onOffline: function() {
    app.testzone.innerHTML += "<br />Offline";
}



}

The below codes were actually in bindEvents at first, but I moved them inside onDeviceReady:

    document.addEventListener("online", this.onOnline,false);
    document.addEventListener("offline", this.onOffline,false);

Upvotes: 0

Views: 761

Answers (2)

user16249416
user16249416

Reputation:

instead of using addEventListener

document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);

use this

if(window.navigator.onLine){ alert('online'); }else{ alert('offline'); }

after adding the "cordova plugin add cordova-plugin-network-information" the window.navigation.onLine will work on mobile

Upvotes: 0

benka
benka

Reputation: 4742

Change the scope of the method calls in your online and offline eventlisteners.

So instead of this.onOnline use app.onOnline (or replace app with the parent).

document.addEventListener("online", app.onOnline,false);
document.addEventListener("offline", app.onOffline,false);

Upvotes: 1

Related Questions