How to delete a localStorage item when the browser window/tab is closed?

To clear a localStorage data on browser close, you can use the window.onunload event to check for tab close.

Let's say you have a local storage object called MyStorage as a global for the sake of this example. Then you can write an event handler −


window.onunload = () => {
   // Clear the local storage

This will clear the local storage on the tab/window close.

Updated on: 27-Nov-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started