Browsing history with history.pushState

Asked

Viewed 329 times

0

Hey there, guys. Next, I made a code for uploading content in Ajax and used history.pushState to change the browser URL, but when I click Back, it doesn’t load the previous address, it just changes the link in the address bar.

How do I click the Back button, besides changing the URL, press 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);
}});
}
  • Doesn’t work? window.location = linkAtual;or window.history.back(0);

2 answers

1

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

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

For this it is necessary to amend var obj = { Title: '', Url: linkMain }; for

var obj = { Title: '', Url: linkAtual };

-1

I resolved with:

$(window).on("popstate", function () {
    var linkAtual = window.location.href;
    AbreEmDIV(linkAtual);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.