Hi All,
I need to cache some javascript variable values across the page.
Consider page 1 has a javascript variable which holds some value and If the user take page 2 and clicks the browser back button the javascript variable value on page 1 will be lost. How can i cache the javascript variable value on page 1. Please help me to solve this issue

Thanks

Dani AI

Generated

Brief recap: JavaScript variables live only in the page's memory, so a fresh reload or a navigation that rebuilds the page will lose them. 's hidden-input idea relies on browser form-state restoration and, as reported, is inconsistent across browsers and navigation paths. For a reliable solution, persist the value outside the in-memory variable.

Recommended approaches and tradeoffs:

  • Use sessionStorage for per-tab persistence while the tab is open (survives back/forward in the same tab). See sessionStorage (MDN).
  • Use localStorage for longer-lived, same-origin persistence across tabs and browser restarts. See localStorage (MDN).
  • Use window.name to keep a string across navigations in the same tab until it is closed (simple and broadly supported). See Window.name (MDN).
  • Use cookies or server-side sessions if the state must be available to the server or shared between devices (cookies are small and transmitted with requests).
    Choose based on lifetime, size, cross-tab needs, and security (do not store secrets client-side).

Quick examples (store/restore using JSON):

// save
sessionStorage.setItem('myVar', JSON.stringify(myVar));

// restore on load
const saved = sessionStorage.getItem('myVar');
if (saved !== null) myVar = JSON.parse(saved);
// using window.name
window.name = JSON.stringify(myVar);
try { myVar = JSON.parse(window.name); } catch (e) { /* ignore */ }

Troubleshooting and cautions: check feature support before use, guard JSON.parse with try/catch, avoid storing sensitive data client-side, and use the pageshow event (persisted flag) if you need to react to bfcache/back-forward restores. For shared or sensitive state, persist on the server and fetch it on page load.

Recommended Answers

All 3 Replies

-Here, try this stunt: (I never tried it)

Write it in the hidden input of the first page - I'm almost sure the Back-Button will not clear its value - and than read it back with your script.

!But, beware that any other way of geting back to the first page, ie clicking a link to it will most certainly clear your var value!

I already tried the technique of using a hidden variable. It didn't work.

can you give me an example of how did you use a "hidden variable" please so I can look into it and see what's the problem?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.