Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to delete a localStorage item when the browser window/tab is closed with JavaScript.

In this article, we’ll look at how to delete a localStorage item when the browser window/tab is closed with JavaScript.

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

To delete a localStorage item when the browser window/tab is closed with JavaScript, we call removeItem.

For instance, we write

window.onbeforeunload = () => {
  window.localStorage.removeItem("keyName");
};

to set window.onbeforeunload to a function that calls localStorage.removeItem with the key of the item to remove.

onbeforeunload is called before we close the tab or window.

Conclusion

To delete a localStorage item when the browser window/tab is closed with JavaScript, we call removeItem.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *