H5 provides two ways to store data on the client:
Localstorage persistent local Storage (browser close re-open data still exists)
Sessionstorage Local storage for a session
These are all done by cookies, which are characterized by a small amount of storage, which is transmitted back and forth between the server and the client, and the transmission efficiency is not high. It is generally possible to determine whether the registered user is logged in to the site.
The WebStorage API inherits from the Window object and provides two new properties-window.localstorage and Window.sessionstorage.
Advantages of WebStorage:
- Increased storage capacity compared to cookies
- You can save the requested form data locally, reduce the HTTP request, and save bandwidth
- WebStorage has an easy-to-use API
Limitations of WebStorage:
- Different browsers WebStorage and Localstorage are not uniform in size.
- Non-readable under browser privacy mode
- is essentially a read of a string, so the page becomes jammed when there is too much storage
- Cannot be crawled by reptiles
Using WebStorage
1. Store Data:
Localstorage.name = ' value ';
localstorage[' name '] = ' value ';
Localstorage.setitem (' name ', ' value ');
Note the keys and values are always strings. Recommended use of the WebStorage API (setitem,getitem,removeitem,key,length)
2. Get the data:
var value = Localstorage.getitem (' name ');
var value = Localstorage.name;
var value = localstorage[' name '];
3. Delete data:
Clear All data
Localstorage.clear ();
Delete specific data;
Localstorage.removeitem (' name ');
4. Detect if the browser supports:
function storageavailable (type) {
try {
var storage = Window[type],
x = ' __storage_test__ ';
Storage.setitem (x, x);
Storage.removeitem (x);
return true;
}
catch (e) {
return false;
}
}
if (storageavailable (' localstorage ')) {
yippee! We can use Localstorage awesomeness
}
else {
Too bad, no localstorage for us
}
5. Is the storage object, we need to convert to a string deposit, wait for the use of the time to remove and then to the object.
var str = json.stringify (obj);
Localstorage.mydata = str;
var obj = json.parse (localstorage.mydata);
Here is the end of the WebStorage basic use of some small summary, I hope you can help.
The webstorage of H5 Web Storage