Web Storage API
The Web Storage API is a straightforward way to store and fetch data in a web browser. It's user-friendly and uncomplicated.
The localStorage Object
The localStorage tool helps store information specifically for a website. You can save, retrieve, add, change, and remove data items connected to that website's domain.
The information is kept without an end date and won't vanish even if you close the browser.
The information will be accessible for periods of days, weeks, and years.
The setItem() Method
The localStorage.setItem() function puts a piece of data into storage.
It needs two things to work: a name and a value.
Example
localStorage.setItem("name", "John Doe");
The getItem() Method
The localStorage.getItem() function gets a piece of data stored in the storage.
The function requires a name as input.
Example
localStorage.getItem("name");
The sessionStorage Object
The sessionStorage object is just like the localStorage object.
The difference is that the sessionStorage holds information for just one session.
Data gets erased once you close the web browser.
The setItem() Method
The sessionStorage.setItem() function saves data in a storage area.
It needs two things: a name and a value.
Example
sessionStorage.setItem("name", "John Doe");
The getItem() Method
The sessionStorage.getItem() function gets a piece of data from storage.
It requires a name as input.
Example
sessionStorage.getItem("name");
Storage Object Properties and Methods
Property/Method | Description |
---|---|
key(n) | Provides the name of the nth key stored. |
length | Shows how many pieces of information are saved in the Storage object. |
getItem(keyname) | Shows what's in the key you're asking about. |
setItem(keyname, value) | Inserts a new key into storage or updates the value of an existing key if it's already there. |
removeItem(keyname) | Deletes the specified key from the storage. |
clear() | Remove all keys from storage. |
Related Pages for Web Storage API
Property | Description |
---|---|
window.localStorage | You can store pairs of information in a web browser. This data doesn't have an expiry date. |
window.sessionStorage | Enables saving pairs of information in a web browser. Holds data for a single session. |