How to Store Data in Web Browser Storage – localStorage and sessionStorage.
The main difference between sessionStorage
and localStorage
is that sessionStorage
only maintains a storage area while the browser is open (including when the page reloads or restores) while localStorage
continues to store data after the browser is closed. In other words, whereas data stored in sessionStorage
is cleared when the page is closed, data stored in localStorage
does not expire.
setItem(key, value)
– Add key and value tosessionStorage
orlocalStorage
.getItem(key)
– This is how you get items fromsessionStorage
orlocalStorage
.removeItem(key)
– remove the key with its value fromsessionStorage
orlocalStorage
.clear()
– Clear all fromsessionStorage
orlocalStorage
.key(index)
– Passed a number to retrieve the key of asessionStorage
orlocalStorage
.length
– The number of stored items.
To save an item value to localStorage or sessionStorage.
localStorage.setItem("Order_id","12345");
or
sessionStorage.setItem("first_name","Vikas");
To get an item value from localStorage or sessionStorage.
localStorage.getItem("Order_id");
or
sessionStorage.getItem("first_name");
To Remove an item with its value from localStorage or sessionStorage.
localStorage.removeItem("Order_id");
or
sessionStorage.removeItem("first_name");
To clear everything from localStorage or sessionStorage.
localStorage.clear();
or
sessionStorage.clear();
To Check the storage name using index from localStorage or sessionStorage.
localStorage.key(0);
localStorage.key(1);
or
sessionStorage.key(0);
sessionStorage.key(1);
To get the no of storage in localStorage or sessionStorage.
localStorage.length;
or
sessionStorage.length;