Summary
Sometimes need to save some data in the browser, especially in the app embedded in the H5 page, need to save some data in the WebView, as the client's data persisted.
There are two ways to store Web Storage in H5: Sessionstorage and Localstorage.
Sessionstorage: Data that is used to store a session, which can only be accessed by a page in the same session, when the session ends, the data is destroyed, so to describe Sessionstorage, a session-level data store.
Localstorage: For persistent local data, data is always present unless it is actively deleted.
The difference between Web storage and cookies
First, they are all stored on the client. However, the size of the cookie is limited, and each time the server is requested, the data in the cookie is taken. Also, a cookie needs to be scoped and not accessible across domains.
Web Storage can be operated more conveniently by means of setitem,getitem,removeitem,clear and so on. Cookies are different, and if you want to use JS to manipulate cookies, you need to encapsulate the method of setting and obtaining cookies yourself.
Compatibility
In addition to the evil ie7-, today's mainstream browsers support Web Storage. You can use the following code to determine whether Web Storage is supported.
if (window.localstorage) { console.log (" support "); Else { console.log ("no support "); };
Localstorage and Sessionstorage
Set the value by SetItem ("Key", "value").
Note that both the key and value are string types. If you want to store JSON, you need to convert the JSON to a JSON string.
Window.localStorage.setItem ("user""wolfy"); Window.localStorage.setItem ("userjson""name" "wolfy" ("Age" ));
GetItem ("key"): Gets key corresponding to value
Console.log ("name", Window.localStorage.getItem ("user"));
Delete
Window.localStorage.removeItem ("user");
Clear all the values
Window.localStorage.clear ();
Summarize
Summing up, here are just a few examples of localstorage usage, similar to seesionstorage. Just because their life cycle is different, sessionstorage is session-level storage, you can understand that when the browser is closed, Sessionstorage is gone, and Localstorage still exists.
[Differences between Html5]sessionstorage and Localstorage