HTML Tutorial
HTML Forms
HTML Graphics
HTML Media
HTML API
HTML Web Storage API
What is HTML Web Storage?
Web storage enables the web applications to store data locally within the user’s browser.
Before HTML5, application data had was stored in cookies for every server request. Web storage is considered to be more secure, and large amounts of data can be stored locally, without putting an impact on the website performance.
HTML Web Storage Objects
HTML web storage provides two objects for storing data on the client:
- localStorage – stores data that has no expiration date.
- sessionStorage – stores data for only one session.
Check browser support for localStorage and sessionStorage ,before using the web storage:
if (typeof(Storage) !== “undefined”) {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}
The localStorage Object
The localStorage object is used to store the data with no expiration date. The data is not deleted even if the browser is closed, and is available the next day, week, or year.
Example explained:
- Create a localStorage name/value pair with name=”lastname” and value=”Smith”
- Retrieve the value of “lastname” and insert it into the element with id=”result”
Another way to write the above example is:
// Store
Click the button to see the counter increase.
Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).
Output:
Click the button to see the counter increase.
Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).
localStorage.removeItem(“lastname”);
The following example counts the number of times the button has been clicked by the user. In this code the value string is converted to a number to be able to increase the counter:
Example
Click the button to see the counter increase.
Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).
The sessionStorage Object
The sessionStorage object is similar to the localStorage object, except that the data is stored for only one session. As soon as the user closes the specific browser tab, the data is deleted.
The following example counts the number of times a user has clicked a button, in the current session:
Example
Click the button to see the counter increase.
Close the browser tab (or window), and try again, and the counter is reset.