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

Spread the love

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

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

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

To delete a localStorage item when the browser window or tab is closed with JavaScript, we can set the window.onbeforeunload property to a function that calls localStorage.removeItem.

For instance, we write

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

to set window.onbeforeunload to a function that calls localStorage.removeItem with key to remove the local storage item with key key when we close the browser window or tab.

Conclusion

To delete a localStorage item when the browser window or tab is closed with JavaScript, we can set the window.onbeforeunload property to a function that calls localStorage.removeItem.

Leave a Reply

Your email address will not be published.