What is HTML5 Web Storage?
Use the Html5,web page to save data locally using the user's browser.
In the past, we usually use cookies to store user data. However, using Web Storage is more secure and faster.
The data is no longer included in each server request, only when you need it. At the same time, we can also save a lot of data without compromising the performance of the site.
Data is saved in key/value form, and a Web page can only access its own data.
Browser support
Ie8+,firefox,chrome. Both opera and Safari 5 support this feature.
Note the IE7 and earlier version numbers do not support this feature.
Localstorage and Sessionstorage
Here are two new properties for saving data:
- Localstorage-save data in a way that has no expiration time
- Sessionstorage-Save data to session
Before using the Web storage, check to see if the browser supports Localstorage and sessionstorage:
- if (typeof(Storage)!=="undefined") {
- yes! Localstorage and Sessionstorage support!
- Some code .....
- }else{
- sorry! No Web Storage support.
- }
Localstorage Object
The Localstorage object holds the problem that the data has no expiration time.
The data is not deleted after the browser is closed. and has been effective.
- Localstorage . LastName = "Smith" ;
- Document . getElementById ("result"). InnerHTML = "Last name:"
- + Localstorage . LastName ;
Online Demo
Code Description:
- A Localstorage key-value pair was created. Use key= "LastName", value= "Smith".
- Get lastname corresponding value, and give Id=result element
Tip: Key-value pairs are stored as strings. Remember to convert them to other formats when necessary.
The following example calculates the number of times a user clicks a button.
In this code, the value will be converted to a number. This enables the use of addition:
- if (localstorage. Clickcount ){
- Localstorage . Clickcount = Number (localstorage. Clickcount ) +1;
- }else{
- Localstorage . Clickcount = 1 ;
- }
- Document . getElementById ("result"). InnerHTML = "You have clicked the button" + localstorage. Clickcount + "time (s)." ;
Online Demo Sessionstorage objects
Sessionstorage objects are similar to Localstorage objects except that the saved data is only valid in the current session. The data will be invalidated when the user closes the browser form.
The following code calculates the number of user clicks in the current session:
- 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." ;
HTML5 's web Storage