Requirements

  • cordova-plugin-dialogs

cordova-plugin-dialogs

Steps

Create a listener for the backbutton

To create a listener for the backbutton you don’t need any plugin. Cordova allows you to listen to a series of events that you can see listed here.

Add this snippet anywhere in your code where you want to create the listener. This is the listener. It will call the  onBackKeyDown() function when the backbutton is activated.

Usually a listener like this would be placed in the index.html or one of your main javascript files since we want to confirm an attempt to exit the app from the start.

Create the dialog asking to confirm the exit

Now we use the plugin cordova-plugin-dialogs as stated here, to create a dialog and check the user has tapped on the confirm button. All this goes inside the onBackKeyDown() function.

onConfirm(buttonIndex) function is called when one of the buttons of the dialog is tapped and the parameter  buttonIndex is the index of that button. That’s why you have to check the index before exiting the app.

The dialog is closed no matter which button has been activated.

Working example