自动清除本地存储 [英] Auto clear localstorage

查看:79
本文介绍了自动清除本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我想在24小时后自动清除localStorage。

我在本地存储的商店开始时间。



任何人都可以帮我或者给我一些提示......





我尝试了什么:



i尝试通过这个setInterval但是我得到了失败

Hello,
I want to automatic clear localStorage after 24 hours.
I was store starting time in localStorage.

Can Anybody help me OR give me hint ...
Please

What I have tried:

i was try to do this setInterval through but i was get failure

推荐答案

你不要T。由于您无法保证您的代码将在24小时内在浏览器上运行,因此无法按计划执行此操作。



您可以做什么但是,当您将数据写入存储时,会使用日期时间戳标记您的数据。当您获取存储数据时,请检查时间戳。如果它超过24小时,请清除存储空间或者不要使用数据。
You don't. Since you can't guarantee your code is going to be running on the browser in 24 hours there is no way to do this on a schedule.

What you can do however is tag your data with a datetime stamp when you write it to storage. When you go get the storage data back, check the timestamp. If it's more than 24 hours old, clear the storage or just don't use the data.


检查这个 localStorage超时 [ ^ ]


无论你做什么,都不能。本地存储是本地存储。在清理时,使用此存储的页面可能无法打开,用户可能根本无法运行浏览器。



首先,您需要考虑使用 sessionStorage 而不是 localStorage Window.sessionStorage - Web API | MDN [ ^ ]。



但是有可能你想在会话之间保留一些数据。然后那样做。唯一的问题是 localStorage ,与 sessionStorage 相比是永久性的,因此,您可能会污染本地存储区域。该怎么办?要回答,我需要了解您的要求。你的24小时规则根本就没有理由。如果你有这样的理由,你需要解释它,但是没有办法在你制定它时实现它,它根本就没有意义。当然,您可以在会话开始时清除本地数据,但取决于当前时间。我不知道为什么你需要那个。最简单的合理设计是为用户提供显式按钮清除本地数据。此按钮可能会出现,具体取决于某些条件,包括时间,或任何您想要的。



另一种方法是在整个会话时间使用会话存储。当用户即将关闭会话时,您可以将会话数据复制到本地数据。一个小小的建议:只有在用户同意的情况下才能做到。



-SA
You cannot, no matter what you do. The local storage is local. At the moment of clean-up, the page using this storage may not be open, the user may not run the browser at all.

First of all, you need to think of using sessionStorage instead of localStorage: Window.sessionStorage — Web APIs | MDN[^].

But it's possible then you want to keep some data between session. Then do exactly that. The only problem is that localStorage, in contrast to sessionStorage is permanent, so, you potentially contaminate the local storage area. What to do? To answer, I need to know your requirements. Your 24-hour rule have no justification at all. If you have such justification, you need to explain it, but there is no a way to implement it as you formulated it, and it makes no sense at all. Of course you can clear the local data on session start, but depending on current time. I have no idea why would you need that. The simplest reasonable design would be giving the user explicit button "Clear local data". This button may appear depending on some conditions, including timing, or whatever you want.

Another approach is using session storage all the session time. When a user is about to close the session, you can copy session data to the local data. One little suggestion: do it only with the user consent.

—SA


这篇关于自动清除本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆