localStorage
is a new API (Application Programming Interface) introduced in HTML5. It is used to store data from website data within the user’s browser.
localStorage
and sessionStorage
, part of the web storage API, are two great tools to save key/value pairs locally. If you click the save button at the top of this post, localStorage
is what’s used to store your saved posts.
Both localStorage and sessionStorage offer advantages compared to using cookies:
Also Local Storage is categorized based on origins. An origin means a domain and a protocol. Data can be accessed and stored by all pages from that origin.
Only strings can be stored with localStorage
or sessionStorage
, but you can use JSON.stringify
to store more complex objects and JSON.parse
to read them:
let obj = { fn: 'Nandu', ln: 'Singh' };
localStorage.setItem("session", JSON.stringify(obj));
let value = JSON.parse(localStorage.getItem("session"));
Delete an entry with the removeItem
method:
localStorage.removeItem(key);
If we need to delete all entries of the store we can simply do:
localStorage.clear();
#localstorage #html5 #javascript