Home >Web Front-end >H5 Tutorial >Detailed explanation of HTML5Web storage examples
HTML5 web storage, a better local storage method than cookie.
What is HTML5 Web Storage?
Using HTML5, you can store user browsing data locally.
Earlier, local storage used cookies. But Web storage needs to be more secure and fast. The data will not be saved on the server, but the data will only be used when users request website data. It can also store large amounts of data without affecting the performance of the website.
Data exists in key/value pairs, and the data of the web page is only allowed to be accessed and used by the web page.
Browser support
Internet Explorer 8+, Firefox, Opera, Chrome, and Safari support Web storage.
Note: Internet Explorer 7 and earlier IE versions do not support web storage.
localStorage and sessionStorage
There are two new objects for storing data on the client:
localStorage - data storage without time limit
sessionStorage - data storage for a session
Before using web storage, you should check whether 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
localStorage object stores data without time limit. The data is still available after the next day, week or year.
Example
localStorage.lastname="Smith";document.getElementById("result").innerHTML="Last name: "+ localStorage.lastname;
Example analysis:
Use key="lastname" and value="Smith" to create a localStorage key/value pair
Retrieve key The value of "lastname" then inserts the data into the element with id="result"
Tip: Key/value pairs are usually stored as strings, you can convert this format according to your needs.
The following example shows the number of times the user clicked the button. The string value in the code is converted to a numeric type:
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).";
sessionStorage object
sessionStorage method collects data for a session storage. When the user closes the browser window, the data will be deleted.
How to create and access a sessionStorage::
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.";
[Related recommendations]
1. Special recommendations : "php Programmer Toolbox" V0.1 version download
2. Free h5 online video tutorial
3. php.cn original html5 video tutorial
The above is the detailed content of Detailed explanation of HTML5Web storage examples. For more information, please follow other related articles on the PHP Chinese website!