There are various events that can be used in Cordova projects. The following table shows the available events.
S.No | Events & Details |
1 | device-ready This event is triggered once Cordova is fully loaded. This helps to ensure that no Cordova functions are called before everything is loaded. |
2 | pause This event is triggered when the app is put into the background. |
3 | resume This event is triggered when the app is returned from the background. |
4 | back button This event is triggered when the back button is pressed. |
5 | menu button This event is triggered when the menu button is pressed. |
6 | search button This event is triggered when the Android search button is pressed. |
7 | start call button This event is triggered when the start call button is pressed. |
8 | end call button This event is triggered when the end call button is pressed. |
9 | volume down button This event is triggered when the volume down button is pressed. |
10 | volume 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.