user2012677
user2012677

Reputation: 5735

History.pushstate can't go back more then once

When I use the following, I can't seem to go back more then once. I tried recommendations from here:

HTML5 history API: cannot go backwards more than once

However, it did not help. Any ideas?

<script>

    $(function () {
        var popped = ('state' in window.history && window.history.state !== null),
            initialURL = location.href;

        //function to handle the scenarios where back and forward buttons used in browser
        $(window).bind("popstate", function (e) {
            // Ignore inital popstate that some browsers fire on page load
            var initialPop = !popped && location.href == initialURL;
            popped = true;
            if (initialPop) {
                return;
            }
            ajaxLoadPage(location.href);
        }); 


            //the ajax function that does the AJAX calls to get the products and load them into the grid
        var ajaxLoadPage = function (url) {
            update_flavors_and_collection(url)
        }




    });

function update_flavors_and_collection(ajax_page){
$("#collection_and_filters").load(ajax_page+" #collection_and_filters", ajax=true, update_history(ajax_page));  
}

function update_history(url){
  if (!history.state || history.state.page!=url)
  history.pushState({ "page": url }, '', url);
}

</script>

Upvotes: 2

Views: 2075

Answers (1)

The first answer of the question you linked is what is actually happening to you. You must read it carefully and understand it better.

You pop one item from the history, then the current history item loads and is pushed again to the history, hence having two times the same item in the history.

When you pop a history item and load a new item, you should NOT push that last item again to the history, as the current history item is the one that you are trying to push.

You can check the last history item and see if is the same, and avoid pushing it, or you can pass a flag to avoid pushing it when you load an item because of popping. The last option is the easiest one.

For example:

$(window).bind("popstate", function (e) {
    [...]
    ajaxLoadPage(location.href, true); // Notice the second argument
});

var ajaxLoadPage = function (url, isPopState) {
    update_flavors_and_collection(url, isPopState);
}

function update_flavors_and_collection(ajax_page, isPopState){
    $("#collection_and_filters").load(ajax_page+" #collection_and_filters", 
    ajax=true, update_history(ajax_page, isPopState));  
}

function update_history(url, isPopState){
    if (!isPopState && (!history.state || history.state.page!=url))
    history.pushState({ "page": url }, '', url);
}

Upvotes: 4

Related Questions