3

I am making an app in HTML5 and javascript and deploying on android device. After confirmation in the application, I don't want it to go back on previous page. But, on the back button of the device it goes on previous page.

I tried many demos. Following is one of the link I tried. http://docs.phonegap.com/en/2.8.0/cordova_events_events.md.html#backbutton

I tried displaying alert for demo purpose. But it does not work.

Please help with your suggestions. Thanks.

I tried the following. It doesn't work. Do I need to add any external jquery file?

<script type="text/javascript" charset="utf-8">
    function onLoad() {
        document.addEventListener("deviceready", onDeviceReady, false);
        alert("On Load");
    }

     function onDeviceReady() {
        document.addEventListener("backbutton", onBackKeyDown, false);
        alert("Device Ready");
    }

    //document.addEventListener('backbutton', onBackKeyDown, false);

    function onBackKeyDown(event) {
        event.preventDefault();
        alert("back pressed");
    }
    </script>
Deepika
  • 331
  • 2
  • 7
  • 20

3 Answers3

1

The proper way to prevent the default behavior of back button is to add the prevent default method:

document.addEventListener('backbutton', onBackKeyDown, false);

function onBackKeyDown(event) {
    // Handle the back button
    event.preventDefault();
    alert('I am a demo purpose alert thingy');
}
TheCodeDestroyer
  • 763
  • 9
  • 29
0

Have a look at the third parameter you pass. It indicates whether the listener uses capture or bubble. You find more information here.

You want to capture the backbutton event at the beginning (capture) and not at the end (bubble).

So try this

document.addEventListener("backbutton", onBackKeyDown, true);

instead of

document.addEventListener('backbutton', onBackKeyDown, false);
COBRA.cH
  • 149
  • 1
  • 11
  • I tried your suggestion, unfortunately it didn't work. – Deepika Mar 24 '14 at 15:52
  • what android version is your phone running? Edit: Also try putting alerts/console before the registration of the event and in the event method, to see if that code is passed. – COBRA.cH Mar 24 '14 at 16:13
  • Ok sry missed that you already have alerts. What I also highly recommend is remote debugging with chrome (needs android 4.0 or higher) see here: https://developers.google.com/chrome-developer-tools/docs/remote-debugging – COBRA.cH Mar 24 '14 at 16:44
0

This is an example I use of the device back button with if else

//device back button functions
document.addEventListener("deviceready", onDeviceReady, false);

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

function onBackKeyDown() {
    if($state.current.name == 'home'){
        // e.preventDefault();
        navigator.app.exitApp();
    } else {
       $state.go('home');
      e.preventDefault();

    }
}
Chris S
  • 231
  • 2
  • 2