Search code examples
javascriptbrowser-history

How to handle history.pushState with content change


While Mozilla has an easy to understand documentation on history.pushState and history.replaceState it doesn't show me how to deal with the content when the back button is pressed and content is changed dynamically.

Suppose foo.html has a form and executes an AJAX call to replace its content on submit, then pushState looks like below:

history.pushState({content:$('#content').html()}, '', 'bar.html');

When the user clicks on the back button the URL changes back to foo.html but the page doesn't display the form. How can I display the form? I had a look at popState but couldn't get it to work properly.


Solution

  • You need to store all of the state you need to re-render the old content, then use that state to re-create the previous page on popstate.

    Model-binding techniques such as Knockout.js (or full MVC frameworks) can make this much easier.