Zack
Zack

Reputation: 4047

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:

Upvotes: 0

Views: 2013

Answers (2)

Alain Stoffels
Alain Stoffels

Reputation: 81

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.

Upvotes: 2

Nick Bull
Nick Bull

Reputation: 9876

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();
    }
}

Upvotes: 2

Related Questions