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
.