MobiDev
MobiDev

Reputation: 55

Navigating between 2 html pages in phonegap

I am working on phonegap application. I am facing one issue.

I have four html pages in my application. Every page contains some widgets like a button or a list view on click of button i move to next page. but when i want to come back on first page i can't. that is when I try to come back using back button of device it closes the app.

I am using device's back button and not user defined, so i need to handle that. same as onBackPressed(); in android.

I know it is because of the WebView widget. but unable to find solution.

I am new to JavaScript, CSS, AJAX, jQuery and HTML5.

How to handle back press in phonegap?

Upvotes: 0

Views: 10190

Answers (3)

Homen
Homen

Reputation: 1212

You can use "backbutton" event for this.

Syntax :

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

And you can write your "yourCallbackFunction" like this.

function yourCallbackFunction(){
    window.history.back();
 }

Link to Documentation

Upvotes: 0

Saxophonist
Saxophonist

Reputation: 707

You can make a workaround to solve this problem.

You can define a function to be triggered when back button is pressed and then verify which page your user is in, and depending on each page run a different action. For example, if he is in page3 then you go back to page 2, if page 2 then go back to page 1 and if he is in page1 you can close the application.

Wrote an example for you:

    <script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
    <script type="text/javascript" charset="utf-8">

    document.addEventListener("deviceready", onDeviceReady, false);

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

    // Handle the back button
    function onBackKeyDown() {
        var whichPage = functionToDetectCurrentPage(); //create a function or detect it somehow
        switch(whichPage){
            case "Page1":
              //works only in android, iOS not quite sure, but heard it's not possible
              //to do programatically
              navigator.app.exitApp();
              break;
            case "Page2":
              window.location = "Page1.html";
              break;
            case "Page3":
              window.location = "Page2.html";
              break;
            case "Page4":
              window.location = "Page2.html";
              break;
        }
    }

Take a look at phonegap documention. http://docs.phonegap.com/en/1.0.0/phonegap_events_events.md.html#backbutton

Let us know whether it helps you!

Upvotes: 2

Andrew Grothe
Andrew Grothe

Reputation: 2374

It may not be possible for an inbrowser app.

See related SO answer at: Handle Android Back Button on Phonegap InAppBrowser

Upvotes: 1

Related Questions