Rudy
Rudy

Reputation: 2353

Phonegap Android back button override

In my Phonegap app, created in a single html file using div as pages, I override the Back button to exit the app, only if the div that acts as the Home page is visible, otherwise to hide the others and show the home div. I use jQuery to attach the event handlers.

It works well at first app launch, but if the app is in the History list, the override is not working, the Back button exits the app without checking which div is visible. After deleting the app from the History list it works as expected again.

Tested on Nexus 4 with Android 4.2. Here is the code:

    $(document).on('backbutton', function (ev) {
        ev.preventDefault();
        if (!$('#divHomeScreen').is(':visible')) {
            $('.screen').hide();
            $('#divHomeScreen').show();
            return false;
        } else {
            navigator.app.exitApp();
        }
    });

Thanks for your help.

Upvotes: 0

Views: 989

Answers (1)

d60402
d60402

Reputation: 3180

What I have done is dynamically add and remove the backbutton handler as needed. For example...

    function showScreen()
    {
      $("#divHomeScreen").hide();
      $(".screen").show();
      $(document).on("backbutton", onBackButton);
    }

    function hideScreen()
    {
      $(".screen").hide();
      $("#divHomeScreen").show();
      $(document).off("backbutton", onBackButton);
    }

    function onBackButton()
    {
      hideScreen();
    }

This was tested on Galaxy S3 Android 4.3 and PhoneGap 3.3.0

Upvotes: 1

Related Questions