mickburkejnr
mickburkejnr

Reputation: 3690

Close Modal Window with back button on Cordova Android app

I'm building a Cordova web app using Bootstrap 3 for HTML and CSS. I am only using the one index.html file, and inside that I use Modal windows for specific actions.

From some initial testing of the app, the most natural thing to do when the modal window displays is to use the back button on the handset to close it. However, when they press this it closes the app down.

I have tried to handle the back button event in a basic way but it doesn't seem to work either on the simulator or on my development handset (Huawei Y300 if this makes a difference). Here is the code below:

// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
    app.receivedEvent('deviceready');

    // Cordova is loaded and it is now safe to call Cordova methods
    //
    function onDeviceReady() {
        // Register the event listener
        document.addEventListener("backbutton", onBackKeyDown, false);
    }

    // Handle the back button
    //
    function onBackKeyDown() {
        // whatever you want to do
        alert('Back button Pressed');
    }
},

I'm fairly sure I know what to do in order to find out if the Modal window is open or not, so I can handle this myself. However, trying to control the back button I can't do.

Upvotes: 0

Views: 1332

Answers (1)

mickburkejnr
mickburkejnr

Reputation: 3690

Having reviewed the code, I decided it was in the wrong place. So I've added the following to my index.js file:

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

function onBackKeyDown(event) {
    event.preventDefault();

    if($("#myModal").hasClass('in')) {
        $("#myModal").modal('hide');
    } else if ($('body').hasClass('mme')){
        $('body').removeClass('mme');
    } else {
        navigator.app.exitApp();
    }

}

Upvotes: 1

Related Questions