HTML5 Web Storage
Using HTML5, the user's browsing data can be stored locally.
Earlier, local storage used cookies. But Web storage needs to be more secure and fast. These data will not be saved on the server, but these 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.
Web Storage of HTML5 local storage
Web Storage is a very important feature introduced by HTML5 and is often used in front-end development. Data can be stored locally on the client, similar to HTML4 cookies, but the functions can be much more powerful than cookies. The cookie size is limited to 4KB, and Web Storage officially recommends 5MB for each website. Web Storage is divided into two types:
sessionStorage
localStorage
literally means It can be clearly seen that sessionStorage saves the data in the session and disappears when the browser is closed; while localStorage always saves the data locally on the client. Unless the data is actively deleted, the data will never expire; regardless of Whether it is sessionStorage or localStorage, the APIs that can be used are the same. The commonly used methods are as follows:
Save data: localStorage.setItem( key, value ); sessionStorage.setItem( key , value );
Read data: localStorage.getItem( key ); sessionStorage.getItem( key );
Delete single data: localStorage.removeItem( key ); sessionStorage.removeItem( key );
Delete all data: localStorage.clear( ); sessionStorage.clear( );
Get the key of an index: localStorage.key( index ); sessionStorage.key( index ) ;
Both have the attribute length indicating the number of keys, that is, the key length:
Before using web storage, you should check whether the browser supports localStorage and sessionStorage:
if(typeof(Storage)! ==="undefined")
{ // Yes! Supports localStorage sessionStorage objects!
// Some code.....
} else {
// Sorry! Web storage is not supported.
}
Example:
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>HTML5--本地存储</title> <script> function clickCounter() { if(typeof(Storage)!=="undefined") { if (localStorage.clickcount) { localStorage.clickcount=Number(localStorage.clickcount)+1; } else { localStorage.clickcount=1; } document.getElementById("result").innerHTML=" 你已经点击了按钮 " + localStorage.clickcount + " 次 "; } else { document.getElementById("result").innerHTML="对不起,您的浏览器不支持 web 存储。"; } } </script> </head> <body> <p><button onclick="clickCounter()" type="button">点我!</button></p> <div id="result"></div> <p>点击该按钮查看计数器的增加。</p> <p>关闭浏览器选项卡(或窗口),重新打开此页面,计数器将继续计数(不是重置)。</p> </body> </html>