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

How to Set Expiration for Data in HTML5 Local Storage?

Susan Sarandon
Release: 2024-10-27 13:57:02
Original
273 people have browsed it

 How to Set Expiration for Data in HTML5 Local Storage?

Data Expiration in HTML5 Local Storage

When utilizing localStorage for storing data in HTML5's DOM Storage, a question arises regarding its expiration. Is there a way to define an expiration period for items saved in local storage?

The local storage API does not provide an explicit mechanism for setting expiration times for individual items. Data remains stored indefinitely or until it is manually deleted or overwritten.

Workaround: Tracking Expiration Using a Timestamp

To address this limitation, it is recommended to incorporate a timestamp directly into the object you store in local storage. This enables you to monitor the data's age and take appropriate actions when necessary.

var object = {value: "value", timestamp: new Date().getTime()}
localStorage.setItem("key", JSON.stringify(object));
Copy after login

Retrieving and Comparing Timestamps

var object = JSON.parse(localStorage.getItem("key")),
    dateString = object.timestamp,
    now = new Date().getTime().toString();

compareTime(dateString, now); //to implement
Copy after login

The compareTime function would compare the stored timestamp with the current time to determine whether the data has expired.

Alternative Solution: localstorage-slim.js

As an alternative to manually handling expiration, consider leveraging a lightweight wrapper library like localstorage-slim.js. This library offers an API for storing objects with automatic expiration management.

The above is the detailed content of How to Set Expiration for Data in HTML5 Local Storage?. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!