I recently made something similar using jQuery, CSS, and HTML.
When user presses the back button, it shows a dialog for 2 seconds, then if user presses back button again, it closes app.
The code below goes in your html files where you want the message to show up.
<div id="dialog" class="dialog">
<span id="dialog_text"></span>
</div>
This code goes in your CSS file. Feel free to change the style if you want.
.dialog{
display: none;
position: fixed;
background-color: rgba(0,0,0,.7);
padding: 10px 20px;
z-index: 1600;
border-radius: 5px;
width: fit-content;
left: 50%;
top: 20%;
transform: translate(-50%, -50%);
}
.dialog span{
padding: 0px;
text-align: center;
font-size: 16px;
}
Next is the jQuery and function. This function when it's called it shows the dialog and hides it after 2 seconds.
function showDialog(message) {
$("#dialog_text").html(message).delay(2000).html();
$("#dialog").fadeIn(250).delay(2000).fadeOut(400);
}
Lastly is the logic. When pressing the back button two times.
This goes in your app.js file
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
var countPress = 0;
document.addEventListener("backbutton", function(e) {
e.preventDefault();
if(countPress >= 1){
navigator.app.exitApp();
}
countPress += 1;
showDialog("Press again to close app");
setTimeout(function(){
countPress = 0;
},3000);
}, false);
/*--------------------End of Device Ready--------------------*/
}
So what this is doing is saving in variable countPress the amount of times the back button has been pressed.
On the addEventListener for the back button, this is checking the countPress variable value whether is equals to or greater than 1, meaning that if back button has been pressed twice, if so, then app closes itself; if not, then it adds 1 to countPress variable and show the dialog function which we call that function like this.
showDialog("any message you want to display on the dialog box);
If user presses back button again, then app closes itself, because now countPress value is 1.
I also included a setTimeout for 3 seconds. After 3 seconds it resets countPress variable to 0. This means that user did not pressed back button again and it could've been just an accident.
Hope this helps and it's understandable. Feel free to use it on your app and share with me any improvement you have done to this. :)