Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

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

My Case: localStorage with key + value that should be deleted when browser is closed and not single tab.

Please see my code if its proper and what can be improved:
//create localStorage key + value if not exist
if(localStorage){
localStorage.myPageDataArr={"name"=>"Dan","lastname"=>"Bonny"};
}

//when browser closed - psedocode
$(window).unload(function(){
localStorage.myPageDataArr=undefined;
});
by

2 Answers

akshay1995
should be done like that and not with delete operator:

localStorage.removeItem(key);
sandhya6gczb
There are five methods to choose from:

setItem(): Add key and value to localStorage
getItem(): Retrieve a value by the key from localStorage
removeItem(): Remove an item by key from localStorage
clear(): Clear all localStorage
key(): Passed a number to retrieve nth key of a localStorage
You can use clear(), this method when invoked clears the entire storage of all records for that domain. It does not receive any parameters.

window.localStorage.clear();

Login / Signup to Answer the Question.