Cordova – Events

There are various events that can be used in Cordova projects. The following table shows the available events.

S.NoEvents & Details
1device-ready This event is triggered once Cordova is fully loaded. This helps to ensure that no Cordova functions are called before everything is loaded.
2pause This event is triggered when the app is put into the background.
3resume This event is triggered when the app is returned from the background.
4back button This event is triggered when the back button is pressed.
5menu button This event is triggered when the menu button is pressed.
6search button This event is triggered when the Android search button is pressed.
7start call button This event is triggered when the start call button is pressed.
8end call button This event is triggered when the end call button is pressed.
9volume down button This event is triggered when the volume down button is pressed.
10volume up button This event is triggered when the volume up button is pressed.

Using Events

All of the events are used almost the same way. We should always add event listeners in our js instead of the inline event calling since the Cordova Content Security Policy doesn’t allow inline Javascript. If we try to call event inline, the following error will be displayed.

The right way of working with events is by using addEventListener. We will understand how to use the volume up button event through an example.

document.addEventListener("volumeupbutton", callbackFunction, false);  
function callbackFunction() { 
   alert('Volume Up Button is pressed!');
}

Once we press the volume up button, the screen will display the following alert.

Handling Back Button

We should use the Android back button for app functionalities like returning to the previous screen. To implement your own functionality, we should first disable the back button that is used to exit the App.

document.addEventListener("backbutton", onBackKeyDown, false);  
function onBackKeyDown(e) { 
   e.preventDefault(); 
   alert('Back Button is Pressed!'); 
} 

Now when we press the native Android back button, the alert will appear on the screen instead of exiting the app. This is done by using the e.preventDefault() command.

Leave a Reply