Ayorus
Ayorus

Reputation: 507

How to enable back and forward buttons when using history.pushState functionality?

I have use the following code to update a seccion in a WebSite. I decided to implement the window.history.pushState functionality. Apparently it is working properly but if I press the back button the address bar will be updated with the correct value but the navegator does not update the page's content.

How can I enable the proper back a forward functionality of the web browser when using pushState?

  ajaxPost("/URLSite", idData, function (data) { //Success
         div.innerHTML = data.Html;
             if (data.Url.length > 0 && window.history.pushState)
                 window.history.pushState({ "html": data.Html, "pageTitle": ' my site: ' + data.Url }, '', '/' + data.Url);

         }, function (cod, Error) { //Error
            var lblMsj = document.getElementById("lblMsj");
             lblMsj.innerHTML =" <br/> " +  Error + " <br/>";
         },null);

Upvotes: 1

Views: 973

Answers (1)

Ayorus
Ayorus

Reputation: 507

@SLaks is right. I reviewed some documentation about onpopState and the following code solved the problem.

window.onpopstate = function (event) {
     if (event.state)
     {
        var divMain = document.getElementById("divMain");
        divMain.innerHTML = event.state.html;
        document.title = event.state.pageTitle;
     }
}

Upvotes: 1

Related Questions