Deepika
Deepika

Reputation: 331

Over-ride the back button of android device through phonegap in javascript

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>

Upvotes: 3

Views: 10517

Answers (3)

Chris S
Chris S

Reputation: 231

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();

    }
}

Upvotes: 0

COBRA.cH
COBRA.cH

Reputation: 147

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);

Upvotes: 0

TheCodeDestroyer
TheCodeDestroyer

Reputation: 762

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');
}

Upvotes: 1

Related Questions