Browsing history with history.pushState

0

Hello everyone. Next, I made a code for loading content in Ajax and I used history.pushState to change the URL of the browser, but when I click on Back, it does not load the previous address, it just changes the link in the address bar.

How do I when to click the Back button, in addition to changing the URL, loading it?

Thank you for your attention!

JS Code:

function AbreEmDIV(endereco){
var linkMain = endereco.replace("ajax", "main")
var divConteudo  = "#conteudo"
var linkAtual = window.location.href
var obj = { Title: '', Url: linkMain };

$.ajax({url: endereco, success: function(result){
    $(divConteudo).html(result);
    window.history.pushState(obj, obj.Title, obj.Url);
}});
}
    
asked by anonymous 21.03.2018 / 14:41

2 answers

0

You can use the onpopstate event to detect when the user clicks back, for example:

window.addEventListener("popstate", event => {
    console.log( event )
    AbreEmDIV( event.state.Url );
});

To do this you need to change var obj = { Title: '', Url: linkMain }; to

var obj = { Title: '', Url: linkAtual };
    
21.03.2018 / 16:26
0

I resolved with:

$(window).on("popstate", function () {
    var linkAtual = window.location.href;
    AbreEmDIV(linkAtual);
});
    
21.03.2018 / 17:34