0

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?
Zack
  • 3,819
  • 3
  • 27
  • 48
  • 1
    Cookies, local storage or include your page state in the url. I prefer the url approach of routes these days, since it allows users to link states to eachother. – Shilly Aug 01 '16 at 15:32
  • Basically, it depends. There are many, many solutions to this problem and it's not practical (especially given the limited information available here) to go into all of them – Liam Aug 01 '16 at 15:33

2 Answers2

2

In most cases I'd say the best way to do this, is to represent the page state in the URL.

Here's why:

  • Because a URL is such a simple concept, this method works regardless of what browser or what privacy settings (e.g. allow cookies and local storage) are used.
  • If User A would send the URL to User B who would like to see the page in the same state, this would still work. This wouldn't be the case for any of your considered methods.

If the variables you want to keep track of are related to a specific user (or session), it would be wiser to track these in some sort of session. This could be both server- or client-side.

Local or session storage (HTML5 Local storage vs. Session storage) are possible solutions, but have some limitations.

  1. Doesn't work in every browser or browser settings (HTML5 local storage isn't supported in older browsers and I know for instance that running Safari in private mode doesn't allow local storage)
  2. If you would send the link to another user he wouldn't see the page in the same state because he hasn't visited the page before, and his local or session storage hasn't been filled with the correct values.
Community
  • 1
  • 1
1

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) {
        data.doStuff();
    }
}
Nick Bull
  • 9,518
  • 6
  • 36
  • 58