Question

I'm writing an Android application for a client. I've been using my own framework for the creation of the app.

This framework works without issue on iPhones, but when I came to apply it to Android/Phonegap I have been getting issues with the back button. My solution was to make a call to the History object to create items as different pages were viewed. The gist of this code is as follows:

        'hook_call': function (name, data, callback, skip_history) {

            if (typeof callback != 'function') {
                callback = function () {};
            }

            app.handlers[name].call(this, data, callback);
            window.app.current_hook = name;

            // Manage history
            if(!skip_history ) {
                history.pushState({'page': name, 'data': data}, null, '#'+name);
            }

        }

My onpopstate function:

// Manage history
window.onpopstate = function(event) {
    try {
        if(window.app.current_hook != event.state.page)
            window.app.hook_call(event.state.page, event.state.data);
    }
    catch(e) {}
};

So, this adds items properly. However if I go say three levels into the history (home, listings -> view_listing) and press back from view_listing I will be taken to the listings section, which is correct, but any further presses leaves me at listings, it won't move any further back than that.

When I look in the log after the navigation steps I just explained, I see these spurious items:

04-16 10:22:39.320: D/CordovaWebView(1148): The current URL is: file:///android_asset/www/index.html#listing
04-16 10:22:39.320: D/CordovaWebView(1148): The URL at item 0 is:file:///android_asset/www/index.html
04-16 10:22:39.400: D/CordovaWebView(1148): The URL at index: 0is file:///android_asset/www/index.html
04-16 10:22:39.400: D/CordovaWebView(1148): The URL at index: 1is file:///android_asset/www/index.html#welcome
04-16 10:22:39.400: D/CordovaWebView(1148): The URL at index: 2is file:///android_asset/www/index.html#listings
04-16 10:22:39.410: D/CordovaWebView(1148): The URL at index: 3is file:///android_asset/www/index.html#listing

I should add that to get to the different pages, hook_call() is called for example when listings are tapped or buttons are pressed.

This scenario is true for any other combination of navigation through the app.

Has anyone had any experience with this or something similar?

Was it helpful?

Solution

I believe your function should look like this, with the skip_history flag set:

// Manage history
window.onpopstate = function(event) {
    try {
        if(window.app.current_hook != event.state.page)
            window.app.hook_call(event.state.page, event.state.data, null, true);
    }
    catch(e) {}
};

Since you don't want to push the history you just popped back onto the stack.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top