Home >Web Front-end >JS Tutorial >How Can I Keep JavaScript Variable Values After Page Refresh?
Retaining JavaScript Variable Values on Page Refresh
In JavaScript, variables typically lose their values when the page is refreshed. To overcome this limitation, we can leverage the window.localStorage or window.sessionStorage methods.
window.localStorage
localStorage allows us to store key-value pairs that persist beyond browser restarts. It applies to the entire website, not just a single page.
To set a variable that should persist after a refresh, use:
var someVarName = "value"; localStorage.setItem("someVarKey", someVarName);
To retrieve the persisted value in any page, use:
var someVarName = localStorage.getItem("someVarKey");
window.sessionStorage
sessionStorage works similarly to localStorage but only persists data as long as the browser tab remains open. It's useful for temporarily storing session-specific information.
To use sessionStorage, replace localStorage with sessionStorage in the above examples.
Considerations:
References:
The above is the detailed content of How Can I Keep JavaScript Variable Values After Page Refresh?. For more information, please follow other related articles on the PHP Chinese website!