With HTML5, web pages can store data locally within the user's browser.
Earlier, this was done with cookies. However, Web Storage is more secure and faster. The data is not included with every server request, but used ONLY when asked for. It is also possible to store large amounts of data, without affecting the website's performance.
The data is stored in key/value pairs, and a web page can only access data stored by itself.
There are two new objects for storing data on the client:
- localStorage - stores data with no expiration date
- sessionStorage - stores data for one session
Before using web storage, check browser support for localStorage and sessionStorage:
The localStorage Object
Example
localStorage.lastname="Smith";
document.getElementById("result").innerHTML="Last name: "
+ localStorage.lastname;
Example explained:
- Create a localStorage key/value pair with key="lastname" and value="Smith"
- Retrieve the value of the "lastname" key and insert it into the element with id="result"
The sessionStorage Object
The sessionStorage object is equal to the localStorage object,
except that it stores the data for only one session. The data is deleted when the user closes the browser window.
The following example counts the number of times a user has clicked a button, in the current session:
Example
if (sessionStorage.clickcount)
{
sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
}
else
{
sessionStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You have clicked the button " + sessionStorage.clickcount + " time(s) in this session.";