I am currently developing a secure web application and I need to ensure that certain sensitive user data stored in localStorage is deleted as soon as the browser window or tab is closed. I am aware that localStorage persists indefinitely, unlike sessionStorage. Is there a reliable JavaScript event listener like "beforeunload" that can handle this cleanup consistently across Chrome and Safari without failing during unexpected crashes?
3 answers
While you can technically use the window.addEventListener('beforeunload', ...) or unload events to run localStorage.removeItem('key'), these are notoriously unreliable. Modern browsers often throttle or ignore synchronous calls during the closing sequence to save power and improve performance. A much more robust architectural approach for Software Development is to use sessionStorage instead. SessionStorage is designed specifically for this lifecycle; it persists through page refreshes but is automatically wiped clean by the browser the moment the tab or window is actually closed, requiring zero manual cleanup code.
Are you dealing with a single-page application (SPA) where the user might accidentally trigger an unload event by refreshing, or is this for a multi-page site where you need the data to persist across different internal links while the tab remains open?
You can try using window.onbeforeunload = function() { localStorage.removeItem('session_key'); }; but keep in mind it might not work if the browser process is killed suddenly.
I agree with Sandra that the code is simple, but as Michelle pointed out in the original post, reliability is the big issue here. For sensitive data, relying on a client-side "onclose" event is risky; it's usually better to manage session expiration on the server-side via tokens.
Kenneth, it is actually a React-based SPA. I want to avoid the data being cleared on a simple page refresh, which is why I initially leaned toward localStorage over sessionStorage. However, if the user closes the tab entirely, that data must be purged for security reasons. If I use the visibilitychange API instead of beforeunload, would that provide a more consistent result across mobile browsers like iOS Safari where traditional unload events often don't fire?