Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript backbutton event listener overrides the android device back button

I have created Android app using cordova 2.6.0. I have implemented a menu feature in my app using html markups and jQuery which toggles on interacting with device's menubutton. But I could not figure out to achieve the following requirement, to behave like a native app.

Requirement

The menu should hide on pressing device's backbutton if the menu is visible. If the menu is not visible the backbutton should now act normally, which is, either it should exit the app or go to the back history.

This is my code

document.addEventListener('deviceready', function(){

document.addEventListener('menubutton', function(){
//Toggle Menu
//Which is working fine
});

document.addEventListener('backbutton', function(){
if(menu is visible) {
  //Hide the menu
  //This is also working fine
return false;
} 

//BUT the default action of backbutton has gone. It cannot exit the app , neither it brings to back history.

//return true;
//I have also tried to return boolean true , but facing the same problem.
});

}, false);

The actual problem

If I attached an eventlistener for backbutton the device's Back Button is disabled, It does not works as normal.

My question is

Is document.addEventListener('backbutton', function(){}); over riding the device's back button? How to get rid of it?

This is happening on Android 4.1.2 Device

like image 447
Lekhnath Avatar asked Sep 25 '13 06:09

Lekhnath


People also ask

How does Cordova handle back button?

Handling Back Button To be able to implement your own functionality, you first need to disable exiting the app when the back button is pressed. Now when we press the native Android back button, the alert will appear on the screen instead of exiting the app. This is done by using e. preventDefault().

How can I tell if my back button is pressed in my phone?

One option is to use jquery mobile. According to this source, to detect the 'back' key, KEYCODE_BACK = 4 on Android.

How does JQuery handle browser back button?

How do I get the browser back button event in JQuery? You can simply fire the “popState” event in JQuery e.g: $(window). on('popstate', function(event) { alert(“pop”); });


1 Answers

Once you have overridden the back button using the listener, it doesn't perform the native functionalities. You have to implement the exit behaviour as well.

In your overriding method, use the following

document.addEventListener('backbutton', function(){
  if(menu is visible) {
       //Hide the menu
       //This is also working fine
   return false;
  }
  else //nothing is visible, exit the app
  {
    navigator.app.exitApp();
  }
});

Hope that helps.

like image 79
SHANK Avatar answered Oct 09 '22 20:10

SHANK