0
votes

I am working on a Phonegap app. The app is ready and now I want to add a back button event while hardware back is pressed (in android).

I have gone through a number of links with no luck.

Can anybody tell me what is the exact way to catch the back button event in a Cordova app for android. My code is below.

index.html

 <script type="text/javascript">
  document.addEventListener("deviceready", onDeviceReady, false);

  alert("====device ready----");
  // PhoneGap is loaded and it is now safe to make calls PhoneGap methods
  function onDeviceReady() {
      // Register the event listener
      document.addEventListener("backbutton", onBackKeyDown, false);
      alert("===back button initializing==");
  }

  // Handle the back button
  function onBackKeyDown() {
    alert("====BACK PRESSED====");
  }  
</script>

When I press the back button, nothing happens.

Can anybody tell me what mistake I have made. Please it has wasted 6 hours. :(

2
Do you ever see the alert for "back button initializing" appear? I would move the alert for "device ready" into onDeviceReady also because as is it's not telling you that the device ready event has occurred. Your code for adding a back button event listener looks correct to me. - Simon Prickett
Nothing happened using this code,no alert is displayed with this code. - JIGAR
do you have a content security policy meta tag? - jcesarmobile
how to check it?i dont know? - JIGAR
I am having only 2 meta tags..with contents. - JIGAR

2 Answers

1
votes
make sure you have installed codova dialogs plugin:-

For example:-

cordova plugin install org.apache.cordova.dialogs

and also add following line:-

document.addEventListener("backbutton", backKeyDown, true);
                navigator.app.overrideBackbutton(true);
                function backKeyDown() {//code here
                }       
0
votes

Please let me know what is the cordova version using now. If you are using cordova version >=4 mean, In cordova.js please do below the changes it will work

//var APP_PLUGIN_NAME = Number(cordova.platformVersion.split('.')[0]) >= 4 ? 'CoreAndroid' : 'App';
var APP_PLUGIN_NAME = 'App';