Zack Teater Zack Teater - 5 months ago 11
Javascript Question

How to maintain page state if user navigates away from page?

I have a page which alters the dom based on user interaction. However, the user might click on a link, which will navigate to an external site. If the user clicks the back button, my page is shown again, but the dom changes do not persist.

What is the best way to keep track of the user interactions so I can rebuild the page on their return?

To maintain state and rebuild the page, I need to keep track of 7-10 variables.

Some ideas I had:

  • server-side session - would require a callback to the server every time a variable changes value?

  • client-side cookies - what if the user disables cookies?

  • hidden form fields - most (all?) browsers locally cache form data, so hitting the back button should retain?


Try the Session variable:

sessionStorage.setItem('key', { "data": "mad data here" });

then to recall it:

var data = sessionStorage.getItem('key');

You could use jQuery as such upon loading the page:

document.load(function() { 
    var data = sessionStorage.getItem('key');
    if (data) {