Improve this

Cordova-specific Features

Onsen UI is great for hybrid app development. This section covers some pitfalls when developing a Cordova app.

Handling ‘deviceready’ event

Cordova APIs can be called after deviceready event is fired. In Onsen UI, ons.ready() function can be used to identify the event.

ons.ready(function() {
  // deviceready event is fired
  // Call whatever Cordova APIs
});

Device Back Button

For Android devices, Cordova fires a backbutton event on hardware back button. It is important to understand that this event is fired by Cordova so it requires cordova.js file or similars (loader.js in Monaca) to be included in the app.

On desktop browsers you can simulate a backbutton event by pressing ESC.

Onsen UI sets handlers with default behavior for Android back button in certain elements:

While this is probably the desired behavior for many apps, Onsen UI allows modifying these handlers for better customization. To change the app’s global handler (closing the app), the ons object provides a few methods:

// Disable or enable
ons.disableDeviceBackButtonHandler();
ons.enableDeviceBackButtonHandler();

// Set a new handler
ons.setDefaultDeviceBackButtonListener(function(event) {
  ons.notification.confirm('Do you want to close the app?') // Ask for confirmation
    .then(function(index) {
      if (index === 1) { // OK button
        navigator.app.exitApp(); // Close the app
      }
    });
});

Apart from this, the mentioned elements together with ons-page element expose a way to modify their own handler:

var myNavigator = document.getElementById('my-navigator');
myNavigator.onDeviceBackButton.disable(); // Disables back button handler
myNavigator.onDeviceBackButton.enable(); // Enables back button handler
myNavigator.onDeviceBackButton.isEnabled(); // Returns true if enabled
myNavigator.onDeviceBackButton.destroy(); // Destroys the current handler

var page = myNavigator.topPage;
page.onDeviceBackButton = function(event) {
  console.log('Hardware back button!');
  event.callParentHandler(); // Calls the parent handler (navigator handler in this case)
};

The event object provided to this handler also contains a event.callParentHandler() method.