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