Search code examples
javascriptandroidcordovaback-button

cordova/phonegap block and allow back button


I am trying to block the back button in certain cases.

However as soon as I add the eventlistener it always blocks the back button.

 document.addEventListener("deviceready", onDeviceReady, false);
 function onDeviceReady() {
      document.addEventListener("backbutton", onBackKey, false);
 }

function onBackKey() {
    if($scope.quicksetup)
    {   
        alert("1");
        return false;
    }   
    else
    {   
        alert("2");
        return true;
    }   
}   

It comes in the else structure but when it returns true it doesn't execute the back action anymore.

There are no errors whatsoever in logcat. I have no idea what is causing this...


Solution

  • Once you set the listener you overwrite the backbutton behaviour no matter if you return true or false it will not execute the normal way anymore.
    You need to use navigator.app.backHistory() and navigator.app.exitApp(); to handle going back and exiting the app.

    The onbackbutton callback does not expect anything to be returned, it is not a boolean callback function.

    function onBackKey() {
        if($scope.quicksetup)
        {   
            alert("1");
            return;
        }   
        else
        {   
            alert("2");
            navigator.app.exitApp(); //I guess you want to exit the app here
        }   
    }