Search code examples
browser-historyhtml5-historypopstate

popstate keeps using last state


I got a simple code when users are filtering brands, categories etc.. Everything works as it should.

BUT when you for example want to go back twice, the first popstate returns the last page perfectly. But when you go back again, it still returns the last page, so it loads it again. And not the page before that one.

A piece of my code:

The pushstate

var params = $('fme_layered_params').value.parseQuery();
// Object { cat="274",  dir="desc"}

if (!params['dir'])
{
    $('fme_layered_params').value += '&dir=' + 'desc';
}
if(window.location.href.indexOf('?') > -1){
    var u = window.location.href.split("?");
    var url = u[0]+"?"+$('fme_layered_params').value;
}else
    var url = window.location.href+"?"+$('fme_layered_params').value;

window.history.pushState($('fme_layered_params').value, 'link', url);

The popstate

window.onpopstate = function(e) {

    if(e.state!==null){
        var state = e.state;
        state = state.split("&");
        // ["cat=272", "dir=desc"]

        jQuery.each(state, function(i,v){
            var info = v.split('=');
            fme_layered_add_params(info[0], info[1], 1);
        });
        fme_layered_make_request();
    }
};

What am i doing wrong?

Thanks in advance!


Solution

  • I solved this problem.
    Every time i went back it also pushed the current page. So i went back and the same page was pushed in history resulting in endless reloading of that certain page.

    TL;DR?
    check, double check, triple check how your code 'walks' through the lines.