Home  >  Article  >  Web Front-end  >  How to set the expiration time of localstorage items

How to set the expiration time of localstorage items

WBOY
WBOYOriginal
2024-01-11 09:06:231859browse

How to set the expiration time of localstorage items

How to set the expiration time of localstorage requires specific code examples

With the rapid development of the Internet, front-end development often requires saving data in the browser. Localstorage is a commonly used Web API that aims to provide a way to store data locally in the browser. However, localstorage does not provide a direct way to set the expiration time. This article will introduce how to set the expiration time of localstorage through code examples.

Before we begin, we first need to understand the basic usage of localstorage. You can use the following two methods to operate localstorage:

  • localStorage.setItem(key, value): Store the specified key-value pair in localstorage.
  • localStorage.getItem(key): Get the value of the specified key from localstorage.

It should be noted that the value stored in localstorage can only be of string type. If you need to store a value of another type, you can use the JSON.stringify() method to convert it to a string, and then use the JSON.parse() method to convert it back to the original type when taking it out.

Next, we will use localstorage to implement the function of setting the expiration time. We can store an expiration timestamp when storing data, and then determine whether it has expired when retrieving the data. The following is a sample code:

// 设置localstorage的过期时间
function setLocalStorageWithExpiration(key, value, expirationMinutes) {
  const expirationMS = expirationMinutes * 60 * 1000;
  const record = {
    value: value,
    expiration: new Date().getTime() + expirationMS
  };
  localStorage.setItem(key, JSON.stringify(record));
}

// 获取localstorage的值(同时判断是否过期)
function getLocalStorageWithExpiration(key) {
  const record = JSON.parse(localStorage.getItem(key));
  if (!record) {
    return null;
  }
  if (new Date().getTime() > record.expiration) {
    localStorage.removeItem(key);
    return null;
  }
  return record.value;
}

// 使用示例
setLocalStorageWithExpiration('username', 'John', 5); // 设置过期时间为5分钟
console.log(getLocalStorageWithExpiration('username')); // 输出:John

// 5分钟后
setTimeout(() => {
  console.log(getLocalStorageWithExpiration('username')); // 输出:null
}, 5 * 60 * 1000);

In the above example, the setLocalStorageWithExpiration function is used to set the expiration time of localstorage. It accepts three parameters: key name, key value, and expiration time expirationMinutes (in minutes). Among them, the expiration time is obtained by calculating the current time plus the specified number of minutes, and then storing the key-value pair and expiration time in localstorage.

getLocalStorageWithExpirationThe function is used to get the value of localstorage and determine whether it has expired. It first gets the value of the specified key from localstorage and parses it into an object. Then determine whether the object exists. If it does not exist or has expired, return null; if it has not expired, return the key value.

In the example, we set up a key-value pair named 'username' and set the expiration time to 5 minutes. After setting up, we get the value of 'username' through the getLocalStorageWithExpiration function and print it to the console. You can see that the output is 'John'. Then, we use the setTimeout function to simulate getting the value of 'username' again after 5 minutes, and print it to the console. You can see that the output is null, indicating that the key-value pair has expired and been removed.

Through the above example, we successfully implemented the function of using localstorage to set the expiration time. It should be reminded that the use of localstorage has certain risks because it is stored in the client browser. Therefore, when using localstorage to store sensitive information or important data, please pay attention to the security and confidentiality of the data.

The above is the detailed content of How to set the expiration time of localstorage items. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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