I have a phonegap app that requires I capture the back button. This works swimmingly but when I am at the main screen and the back button is pressed I want to call the original event handler and let the app close or do whatever comes naturally to the platform with such a press. I know I can tell the app to quit but understand this is bad form for iPhone apps.
No matter what I try (and I have tried many things) I cannot get the original handler to fire. Any advice?
In my code I have a switch statement inside my backbutton event handler that directs the app as needed to the effect of:
switch blahBlah
{
    case 'this' :
        doThis() ;
        break;
    case 'main' :
        // What do I do here that is well behaved for all platforms??? 
        break;
    default:
        doFoo() ;
} 
                Detect whenever you land on the main screen and remove your custom event handler.
document.removeEventListener( "backbutton", function(){}, false );
and add the event listener on the other pages (or sections).
document.addEventListener( "backbutton", OverrideBackButton, false );
Hope that helps.
This is what I've used and it seems to work fine for my needs
        function pageinit() {
            document.addEventListener("deviceready", deviceInfo, true);
        }
        function deviceInfo() {
            document.addEventListener("backbutton", onBackButton, true);
        } 
        function onBackButton(e) {
            try{
                var activePage = $.mobile.activePage.attr('id');
                if(activePage == 'Options'){
                    closeOptions();
                } else if(activePage == 'Popup'){
                    closePopup();
                } else if(activePage == 'HomePage'){
                function checkButtonSelection(iValue){
                    if (iValue == 2){
                            navigator.app.exitApp();
                        }
                    }
                e.preventDefault();
                navigator.notification.confirm(
                    "Are you sure you want to EXIT the program?",
                    checkButtonSelection,
                    'EXIT APP:',
                    'Cancel,OK');
                } else {
                     navigator.app.backHistory();
                }
            } catch(e){ console.log('Exception: '+e,3); }
        }
Hope this helps...
Cordova 7.x, at least on Android, doesn't seem to properly update the override state. As a consequence, @SHANK's answer doesn't work anymore.
As a workaround, you can disable back button overriding manually, resulting in default behavior:
navigator.app.overrideBackbutton(false);
To re-active custom handling, analogously do:
navigator.app.overrideBackbutton(true);
I filed a bug report on Apache's issue tracker regarding this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With