1-4-25
HTML web storage; better than cookies.
With web storage, web applications can store data locally within the user's browser.
Before HTML5, application data had to be stored in cookies, incuded in every server request. Web storage is more secure is more secure, and large amounts of data can be stored locally, without affecting website performance.
Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Web storage is per orgin (per domain and protocal). All pages, from one orgin, can store and access the same data.
HTML web storage provides two object for storing data on the client:
Before using web storage, check browser support for localStorage and sessionStorage:
if (typeof(Storage) !== "undefined") { // Code for localStorage/sessionSorage. } else { // Sorry! No Web Storage support.. }
The localStorage object stores the data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year.
Example explained:
The example above could also be written like this:
// Store localStorage.lastname = "Smith"; //Retrieve document.getElementById("result").innerHTML = localStorage.lastname;
The syntax for removing the "lastname" localStorage item is as follows:
localStorage.removeItem("lastname");
Note: Name/value pairs are always stored as strings, Remember to convert them to another format when needed!
The following example counts the number of times a user has clicked a button. In this code the value string is converted to a number to be able to increase the counter:
Click the button to see the counter increase.
Close the browser tab (or window), and try again, and counter will continue to count (is not reset).
The sessionStorage object is eaqual to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.
The following example counts the number of times a user has clicked a button, in the current session:
Click the button to see the counter increase.
Close the browser tab (or window), and try again, and the counter is reset.