Home >Web Front-end >H5 Tutorial >HTML5 local storage application sessionStorage and localStorage
Before html5, browsers usually used cookies to store data, but cookies had domain name and size limits.
After html5 became popular, browser-side data storage could be achieved through localStorage and sessionStorage. , what are the characteristics of these two?
sessionStorage
SessionStorage belongs to a temporary session. The validity period of data storage is: the time period from the opening of the page to the closing of the page. It belongs to the temporary storage of the window. When the page is closed, the local storage disappears
localStorage
Permanent storage (data can be deleted manually)
Storage limit (5M)
The client is completed and will not request the server to process
sessionStorage data cannot be shared between pages, but localStorage can be shared between pages
Application of sessionStorage:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script> window.onload = function(){ var aInput = document.getElementsByTagName('input'); aInput[0].onclick = function(){ //sessionStorage: 临时存储, 只在当前页面有效,不能传递到其他页面,页面关闭之后消失 window.sessionStorage.setItem("name", aInput[3].value ); }; aInput[1].onclick = function(){ alert(window.sessionStorage.getItem("name" )); }; aInput[2].onclick = function(){ window.sessionStorage.removeItem("name" ); }; } </script> </head> <body> <input type="button" value="设置" /> <input type="button" value="获取" /> <input type="button" value="删除" /> <br/> <input type="text" /> </body> </html>
##Application of localStorage
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script> window.onload = function(){ var aInput = document.getElementsByTagName('input'); aInput[0].onclick = function(){ //localStorage : 永久性存储 window.localStorage.setItem("name", aInput[3].value); window.localStorage.setItem("name2", 'aaaaa'); }; aInput[1].onclick = function(){ alert( window.localStorage.getItem( "name" ) ); alert( window.localStorage.getItem( "name2" ) ); }; aInput[2].onclick = function(){ window.localStorage.removeItem("name"); // window.localStorage.clear(); }; } </script> </head> <body> <input type="button" value="设置" /> <input type="button" value="获取" /> <input type="button" value="删除" /> <br/> <input type="text" /> </body> </html>rrree
The above is the detailed content of HTML5 local storage application sessionStorage and localStorage. For more information, please follow other related articles on the PHP Chinese website!