Skip to content

Instantly share code, notes, and snippets.

@kuldipem
Created July 12, 2016 19:36
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save kuldipem/6acfc65dbbbb61e11e2dea95fbb37227 to your computer and use it in GitHub Desktop.
Save kuldipem/6acfc65dbbbb61e11e2dea95fbb37227 to your computer and use it in GitHub Desktop.
Cordova/PhoneGap exit app after twice press back button with toast ( plugin required https://github.com/EddyVerbruggen/Toast-PhoneGap-Plugin )
var lastTimeBackPress=0;
var timePeriodToExit=2000;
function onBackKeyDown(e){
e.preventDefault();
e.stopPropagation();
if(new Date().getTime() - lastTimeBackPress < timePeriodToExit){
navigator.app.exitApp();
}else{
window.plugins.toast.showWithOptions(
{
message: "Press again to exit.",
duration: "short", // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
position: "bottom",
addPixelsY: -40 // added a negative value to move it up a bit (default 0)
}
);
lastTimeBackPress=new Date().getTime();
}
};
document.addEventListener("backbutton", onBackKeyDown, false);
@pat2echo
Copy link

To disable the default behavior of the back button on android devices simply register an event handler for the back button. This would prevent the back button from closing the application.

Code shown below is specifically for Framework7

$(document).on('page:beforeinit', function (e) {
if( $.fn.hyellaIMenu.mainView.history && $.fn.hyellaIMenu.mainView.history.length > 1 ){
    document.addEventListener( "backbutton", disableBackButton, false );
}
});

function disableBackButton( e ){
    if( $.fn.hyellaIMenu.mainView.history && $.fn.hyellaIMenu.mainView.history.length < 3 ){
        document.removeEventListener("backbutton", disableBackButton );
    }

if( $.fn.hyellaIMenu.mainView.history && $.fn.hyellaIMenu.mainView.history.length > 1 ){
    $.fn.hyellaIMenu.mainView.router.back();
}
};

To override the default back-button behavior, register an event listener for the backbutton event.

NOTE: It is no longer necessary to call any other method to override the back-button behavior.

https://cordova.apache.org/docs/en/latest/cordova/events/events.html#backbutton

@AiltonRamos
Copy link

Hi, I'm using google translate to send you the message. Anyway, I've reused your "app-exit.js" script. Worked perfectly. So, how can I do it when my modal materialize is open, can not quit the application? If the modal is not open, you can quit the application. And that the user exits the modal only by the option of the exit button of the modal itself?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment