Browser back button does not work after history.pushstate ()

1

I'm working on a page that loads part of the content by javascript. I am succeeding and even generates and adds a new url to the browser history.

function FiltraItens(criterio){
var UrlJson = baseUrl + "//Json/Listas/ListarItens/";

$.ajax({
method: "GET",
    url: UrlJson,
    traditional: true,
    data:
    {
    Criterio: criterio
    },
    beforeSend: function() {
        $("div.itens").empty();
    },
    success: function(view) {
        $("div.itens").append(view);

        var NovaUrl = "";
        if (OldUrlBuscaOuEstado !== "busca")
        {
            NovaUrl = "?criterio=" + criterio;
            window.history.pushState('Object', criterio, NovaUrl);
        }

    },
    error: function(data) {
        alert("Falha! Não foi possível retornar os itens, por favor, tente novamente mais tarde.");
    }

});

return false;}

Htmt looks like this:

<a href="#ResultadoBusca" onclick="FiltraItens(2)" >carrega itens2</a>

My problem is that by clicking on the back button of the browser the url displayed until it changes, however the content of the page is not retrieved, remaining the same.

It seems like I have to add the popstate listener. But I have no idea how. I already researched many sites and I can not understand ...

    
asked by anonymous 16.03.2018 / 13:34

1 answer

1

Really missing the popstate. From what i understand window.history.pushState is used to change history.state. And the window.history.popstate is monitoring when a command to return to the previous page will be done. Then execute what is in it.

The html remained the same. The code has changed a bit and it looks like this:

function FiltraItens(criterio){
    var UrlJson = baseUrl + "//Json/Listas/ListarItens/";
    $.ajax({
    method: "GET",
        url: UrlJson,
        traditional: true,
        data:
        {
        Criterio: criterio
        },
        beforeSend: function() {
            $("div.itens").empty();
        },
        success: function(view) {
            $("div.itens").append(view);

            var NovaUrl = "";
            if (OldUrlBuscaOuEstado !== "busca")
            {
                NovaUrl = "?criterio=" + criterio;
                var dados[];
                var dados["Criterio"] = criterio;
                window.history.pushState(dados, criterio, NovaUrl);
            }

        },
        error: function(data) {
             alert("Falha! Não foi possível retornar os itens, por favor, tente novamente mais tarde.");
        }
    });
    return false;
}

In addition I added to the page load event:

window.onload = function () {
    var dados = {};
    dados["Criterio"] = "um criterio padrão";
    window.history.replaceState(data, null, null);
};

And finally to the popstate event

$(window).on("popstate", function () {
    var Criterio = history.state.Criterio;
    FiltraItens(Criterio);
});
    
16.03.2018 / 19:00