michele
michele

Reputation: 26598

PhoneGap handle back button to not close the app

I have index.html and page.html

index.html has an anchor to page.html

I would the backbutton press and ask to the user if he really want go back to index.html

This is my code:

index.html

<!DOCTYPE HTML>
<html>
  <head>
    <title>First App</title>
    <script src="cordova-2.6.0.js"></script>
    <script>
     function onLoad(){
          document.addEventListener("deviceready",onDeviceReady, true);
     }

     function onDeviceReady(){
        navigator.notification.alert("PhoneGap is working!!");
     }
  </script>
  </head>
  <body onload="onLoad();">
       <h1>Welcome to PhoneGap</h1>
       <h2>Edit assets/www/index.html</h2>
        <a href="page.html">Go to page</a>
  </body>
</html>

page.html

<!DOCTYPE HTML>
<html>
  <head>
    <title>First App</title>
  <script src="cordova-2.6.0.js"></script>
  <script>
     function onLoad(){
          document.addEventListener("deviceready",onDeviceReady, true);
        document.addEventListener("backbutton", onBackKeyDown, false);
     }

     function onDeviceReady(){
navigator.notification.alert("PhoneGap is working!!");
     }

function onBackKeyDown(e) {        
        navigator.notification.alert("PhoneGap back is working!!");
}
  </script>
  </head>
  <body onload="onLoad();">
       <h1>Welcome to PhoneGap Page</h1>
       <h2>Edit assets/www/page.html</h2>
  </body>
</html>

The problem is that the back button press is not handled, but cordova is loaded correctly because I have the alert box showed.

What I am doing wrong?

I have a Samsung Google Nexus with Android 4.2.2

Thanks a lot.

Upvotes: 0

Views: 2145

Answers (1)

Uncharted Space
Uncharted Space

Reputation: 861

Put your back button listener inside of the onDeviceReady function.

Upvotes: 3

Related Questions