Home > Web Front-end > JS Tutorial > body text

How Can I Keep JavaScript Variables After Page Refresh?

Linda Hamilton
Release: 2024-11-25 04:59:21
Original
707 people have browsed it

How Can I Keep JavaScript Variables After Page Refresh?

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:

  • localStorage: Data persists indefinitely across browser sessions and restarts.
  • sessionStorage: Data persists only during the current browser session and is cleared once the window or tab is closed.

Storing Data:

To store a variable in persistent storage, use setItem() with the desired key and value:

var someVarName = "value";
localStorage.setItem("someVarKey", someVarName);
Copy after login

Retrieving Data:

After the page refresh, retrieve the stored data using getItem():

var someVarName = localStorage.getItem("someVarKey");
Copy after login

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));
Copy after login

Retrieve and parse the data later:

var obj = JSON.parse(localStorage.getItem("objKey"));
Copy after login

Additional Resources:

  • Browser Storage: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
  • LocalStorage: https://developer.mozilla.org/en-US/docs/DOM/Storage#localStorage

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template