Home > Article > Web Front-end > HTML5 client data storageWeb Storage—localStorage and sessionStorage
HTML5 provides a new method of storing data on the client side Web Storage
Similar to Cookie in HTML4
But it is much more powerful
Let’s briefly review the cookies used before
Cookies store data on the user’s device. The amount of data stored is small, only 4KB
Yes Detect whether cookies are enabled through navigator.cookieEnabled
Set cookies document.cookie = 'key=value';
Get cookie document.cookie;
Delete cookie document.cookie = "key=value;max-age=0";
Set max-age storage perioddocument.cookie = "key=value;max-age=1000"; // 1000 seconds
Set expires storage period
var timestamp = (new Date()).getTime() + 10000;var expires = new Date(timestamp).toGMTString(); //或toUTCStringdocument.cookie = "key=value;expires="+expires;
Get specific cookie value
function getCookie(name) { var name = name + "="; var ary = document.cookie.split(';'); for(var i = 0; i < ary.length; i++){ var c = ary[i]; while (c.charAt(0) == ' '){ c = c.substring(1); } if (c.indexOf(name) != -1){ return c.substring(name.length, c.length); } } return ""; }
Web Storage is divided into two types
localStorage and sessionStorage
The difference is:
localStorage stores permanent data unless manually deleted
sessionStorage stores temporary data and will disappear when the window is closed
Web Storage can only store string data
I think they can be understood as JSON
The usage methods are similar, taking localStorage as an example
localStorage.name = 'payen'; localStorage.info = JSON.stringify({name: 'payen', age: 20}); console.log(localStorage.name); console.log(JSON.parse(localStorage.info));
The name of the data to be stored is the attribute name of localStorage
Ordinary strings can be stored normally That’s it
Object data can be converted to string format using JSON.stringify()
When used, JSON.parse() can be used to convert it back to object format
(If the object is stored directly, it will Forced to be converted into a string "[object Object]")
To delete the data, just delete it
delete localStorage.name;delete localStorage.info;
If you do not delete it, the data in localStorage will always exist for you. The browser
localStorage and sessionStorage also provide a simple API
Similar to a client database
(APIs are the same)
Commonly used There are the following:
Save data setItem(key, value)
Read data getItem(key)
Delete a single data removeItem(key)
Clear all data clearItem()
Get the data index key(index)
Through this, we can write a simple address book
<p id="container"> <br> <label for="username">姓名:</label> <input type="text" id="username" name="username"> <br> <label for="mobilephone">手机:</label> <input type="text" id="mobilephone" name="mobilephone"> <br><br> <input type="button" onclick="add()" id="add" value="增加联系人"> <br><br> <hr> <label for="search">输入姓名:</label> <input type="text" id="search" name="search"> <br><br> <input type="button" onclick="find()" id="find" value="查找手机号"> <p id="result"><br></p></p>
#container { border: 2px solid gray; width: 320px; text-align:center;}##It is implemented in JavaScript These two functions
var user = document.getElementById('username'), phone = document.getElementById('mobilephone'), search = document.getElementById('search'), result = document.getElementById('result');var add = function(){ var u = user.value, p = phone.value, l = localStorage.length; if(u !== '' && p !== ''){ localStorage.setItem(u, p); user.value = ''; phone.value = ''; alert('添加成功'); } };var find = function(){ var s = search.value, r = localStorage.getItem(s); if(s !== '' && r){ result.innerHTML = r; } };Enter the name and mobile phone number to add a contact
Then enter the contact name below and we can find the mobile phone number
You can also add it to display all the information in the address book
Delete contact function, etc.
Cookie | Web Storage | |
---|---|---|
is generally generated by the server and sets the time; generated by the browser, it is closed by default and the browser fails | local : Save permanently if not cleared; session: Close the page or the browser is invalid | |
4KB | Official recommendation 5MB | |
Carried in the HTTP header (excessive use may cause performance problems) | Only stored in the browser, does not participate in communication | |
The native interface is not friendly and needs to be encapsulated manually | The native interface is friendly |