Al Mr
Al Mr

Reputation: 123

Problems with addEventListener('deviceready') in cordova app

I'm trying to use "Cordova Local-Notification Plugin" in my cordova application without success. For example, the following doesn't work:

console.log(now);

document.addEventListener('deviceready', function() {
    var now = new Date().getTime(),
    _5_sec_from_now = new Date(now + 5 * 1000);
    console.log(now);
    cordova.plugins.notification.local.schedule({
        text:"Delayed Notification",
        at:_5_sec_from_now,
        led:"FF0000",
        sound:null
    });
}, false);

Upvotes: 0

Views: 624

Answers (1)

Phil Poore
Phil Poore

Reputation: 2256

Cordova deviceready not firing

Check you are including cordova.js or phonegap.js in your index.html

If Cordova is not loaded, the event will not be fired.

Also check for any console errors in Xcode.

Using Web Inspector to Debug Mobile Safari

You can use Safari to inspect Cordova apps running on real devices.

More info here:

https://webdesign.tutsplus.com/articles/quick-tip-using-web-inspector-to-debug-mobile-safari--webdesign-8787

enter image description here

When working in the browser, deviceready does not fire, it only fires on a real device. This also means you can't test the plugins easily in the browser.

To get around this, you can detect if cordova is loaded and call and setup function yourself.

function setup() {
    var now = new Date().getTime(),
    _5_sec_from_now = new Date(now + 5 * 1000);
    console.log(now);

    // ** this will not work in browser **
    cordova.plugins.notification.local.schedule({
        text:"Delayed Notification",
        at:_5_sec_from_now,
        led:"FF0000",
        sound:null
    });
}


// check if codova is loaded
if (!!window.cordova){
    // running on device
    // wait for plugins to load
    document.addEventListener('deviceready', setup, false);    
}else{
    // running in browser
    // call setup anyway
    setTimeout(setup, 200);
}

Upvotes: 1

Related Questions