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

Yosef picture Yosef · Mar 30, 2012 · Viewed 606.9k times · Source

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;
});

Answer

Yosef picture Yosef · May 22, 2012

should be done like that and not with delete operator:

localStorage.removeItem(key);