Hello, I am able to add localStorage using Item keys using Javascript, with below sample code
localStorage.setItem("test", "TestValue");
But I would like to know, how can I clear localStorage using Javascript, and how to remove all localStorage keys using single code.
You can clear or delete key in localStorage using Javascript as per below example
localStorage.removeItem("KeyName"); //remove item from local storage based on key name
To Clear all keys at once
localStorage.clear(); //clear all key at once
To Retrieve value based on keys
// Retrieve the object from storage
var retrievedValue = localStorage.getItem('YourKeyName');
Read Local storage in javascript for more complete details about localStorage in Javascript.
You should use "window" to remove global storage
window.localStorage.removeItem('KeyName');
OR
If you want to delete or clear local storage on windows load
window.onbeforeunload = function() {
localStorage.removeItem(key);
return '';
};
This should work.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly