Preserving JavaScript Variables Beyond Page Refresh
In JavaScript, it's possible to modify variables dynamically through button clicks or other events. However, by default, these changes are lost when the page refreshes. How can we ensure that variables retain their values even after refreshing the page?
Local and Session Storage
Persistent storage in JavaScript is achieved through two methods: window.localStorage and window.sessionStorage. Both provide a means to store key-value pairs, with subtle differences:
Storing Data:
To store a variable in persistent storage, use setItem() with the desired key and value:
var someVarName = "value"; localStorage.setItem("someVarKey", someVarName);
Retrieving Data:
After the page refresh, retrieve the stored data using getItem():
var someVarName = localStorage.getItem("someVarKey");
This will assign the stored value to someVarName, even after the page has been refreshed.
Overcoming Limitations:
Local and session storage only support string values. To store more complex data types, consider using JSON:
var obj = { prop1: "value1", prop2: "value2" }; localStorage.setItem("objKey", JSON.stringify(obj));
Retrieve and parse the data later:
var obj = JSON.parse(localStorage.getItem("objKey"));
Additional Resources:
The above is the detailed content of How Can I Keep JavaScript Variables After Page Refresh?. For more information, please follow other related articles on the PHP Chinese website!