The storage scheme of H5 refers to the data storage on the client side, which needs to be understood. Is there any storage scheme available before this? Of course there are, cookies that I’ve been using, and if you read my article on client-side storage, it makes a lot of sense, because I talked about the disadvantages and advantages of cookies. So today we are talking about the storage solution that H5 just put forward: localStorage and sessionStorage

First of all, why do we need this thing, why do we have cookies before but H5 redefines these two parts by storing them on the client side? As we all know, the interaction between the client and the server is usually request is sent in the past, and then pass the data on the server to come back, this is a kind of conventional treatment method, but in fact, we know that a lot of time, the client sends the request of many are repeated, or request the amount of data is not large, this time we chose to temporary data exist cookies here, Logs in routine practice, so the cookie store only 4 k, is caused by the user only can request a small data, so that in does not affect the performance of the case, how can be as much as possible, will be more data stored in the client is called a kind of idea and trend, this result is that the user experience will be better, Because after all, the speed will be much faster, that’s one thing, plus, the server will be less stressed. Said so much nonsense, just to illustrate the importance of today’s article.

Let’s talk about how to use it:

First is based on JS implementation, so our code must be written in JS.

I have also written specific examples in the past: localStore example, today simply write again, using the official example:

<! DOCTYPEhtml>
<html>
<body>
<div id="result"></div>
<script>
// Check browser support
if (typeof(Storage) ! = ="undefined") {
    // Store
    localStorage.setItem("lastname"."Gates");
    // Retrieve
    document.getElementById("result").innerHTML = localStorage.getItem("lastname");
} else {
    document.getElementById("result").innerHTML = "I'm sorry! Your browser does not support Web Storage...";
}
</script>
</body>
</html>
Copy the code

There are two basic usages that come up, and they’re the ones we use most often

Localstorage.setitem ("key","value"Copy the code
Localstorage.getitem ("key") // Enter the key when needed to get the corresponding dataCopy the code

Here are his characteristics:

There is no time limit or refresh time limit, but there is a browser limit (that is, it also follows the same origin policy)

Here’s an example:

<! DOCTYPEHTML>
<html>
	<meta charset="UTF-8"/>
<body>
<script type="text/javascript">
	if (localStorage.pagecount)
		{
		localStorage.pagecount=Number(localStorage.pagecount) +1;
		}
	else
		{
		localStorage.pagecount=1;
		}
	document.write("Visits: " + localStorage.pagecount + " time(s).");
	</script> 
	<p>Refresh the page to see that the counter is growing.</p>
	<p>Please close your browser window and try again. The counter will continue counting.</p>
</body>
</html>
Copy the code

(Source code from W3cshool)

Instead of switching browsers, I keep refreshing and it looks like this:

\

I close the browser to open again or continue to count, so that the browser as long as the same is no problem.

This is what happens when we switch to a different browser:

\

Obviously, it’s reset by changing the browser, so we can guess how it works, but it’s actually implemented based on cookies, based on the browser’s cache.

Ok, here basically normal use this is no problem, then some people have said, for the login is no problem, the user also to refresh the page, but according to this, the user is logged off, withdrew, isn’t re-enter will still have their own information, wouldn’t it be very not safe, also not routine practice, right, So we say below, how to clear the local data, some people cancel, information can be imagined must be should disappear, how to clear it?

localStorage.clear;
Copy the code

Clear all the contents of the page:

var storage=window.localStorage; storage.a=1; storage.setItem("c",3); console.log(storage); storage.clear(); console.log(storage); // Source code from Xie Canyong's blog gardenCopy the code

The supported versions are:

\

(Picture from Xie Canyong’s blog garden)

Check whether the browser supports localStorage:

If (! LocalStorage){alert(" Browser supports localStorage "); return false; }else{// main logic business} // source code extracted from Xie Canyong's blog gardenCopy the code

Write to localStorage in three ways:

If (! LocalStorage){alert(" Browser supports localStorage "); return false; }else{ var storage=window.localStorage; Storage ["a"]=1; Storage. A =1; SetItem ("c",3); console.log(typeof storage["a"]); console.log(typeof storage["b"]); console.log(typeof storage["c"]); }Copy the code

To read:

if(! LocalStorage){alert(" Browser supports localStorage "); }else{ var storage=window.localStorage; Storage ["a"]=1; Storage. A =1; SetItem ("c",3); console.log(typeof storage["a"]); console.log(typeof storage["b"]); console.log(typeof storage["c"]); Var a=storage.a; console.log(a); Var b=storage["b"]; console.log(b); Var c= storage.getitem ("c"); console.log(c); }Copy the code

Delete a key data:

var storage=window.localStorage;
            storage.a=1;
            storage.setItem("c",3);
            console.log(storage);
            storage.removeItem("a");
            console.log(storage.a);
Copy the code

Finally, if we store json data in localStorage, we know that localStorage automatically converts the data to String. What we need to do is json.stringify () converts the json data to jsonString

if(! LocalStorage){alert(" Browser supports localStorage "); }else{ var storage=window.localStorage; var data={ name:'xiecanyong', sex:'man', hobby:'program' }; var d=JSON.stringify(data); storage.setItem("data",d); console.log(storage.data); }Copy the code

Example 2:

var obj = { name:'Jim' }; var str = JSON.stringify(obj); // Store sessionstorage. obj = STR;Copy the code
// read STR = sessionstorage.obj; Parse (STR); // Convert to object obj = json.parse (STR);Copy the code

The data jsonString is then converted into a JSON object

var storage=window.localStorage; var data={ name:'xiecanyong', sex:'man', hobby:'program' }; var d=JSON.stringify(data); storage.setItem("data",d); // Convert JSON string to JSON object var JSON = storage.getitem ("data"); var jsonObj=JSON.parse(json); console.log(typeof jsonObj);Copy the code

Finally, let’s briefly talk about its limitations. After all, when something comes out, it certainly does not have advantages and disadvantages. Its disadvantages are as follows:

1. Versions earlier than Internet Explorer 8 are not supported

2. Most existing browsers store data as strings, so as I mentioned above, if it is JSON, it needs to be converted.

3, browser privacy mode is not available

4, its storage space is very large, about 5M, so if we store everything on the page, in fact, we do not recommend this use, the result is that the page becomes very jammed.

Summary:

LocalStorage is an instance of type Storage. There are several methods: ①clear () : delete all values. ②getItem (name) : obtains the corresponding value based on the specified name ③ Key (index) : obtains the name of the specified digit position. ⑤setItem(name,value) : sets a corresponding value for the specified nameCopy the code

Next we introduce sessionStorage

The usage is the same, but the difference is that it erases data by simply closing the browser.

Summary features:

1) Same-origin policy restriction. If you want to use the same sessionStorage between different pages, the pages must be under the same protocol, host name, and port. (IE 8 and 9 store data based on the same host name, ignoring protocol (HTTP and HTTPS) and port number requirements.) 2) Single-tab restriction. SessionStorage operations are limited to a single TAB page. All same-origin page accesses from this TAB page can share sessionStorage data. 3) Store only locally. SeesionStorage data will not be sent to the server along with HTTP requests. The data takes effect locally and is cleared after the seesionStorage TAB is closed. (If you use Chrome's Recovery TAB function, seesionStorage data will also be restored.) 4) Storage mode. The storage mode of seesionStorage is key and value. The value of value must be a string. (If passed a non-string, it will also be converted to a string when stored. The true value is converted to "true"). 5) Storage limit: Different browsers have different storage limits, but most browsers limit the limit to less than 5MB.Copy the code

I don’t want to say anything else. Have what do not understand, can leave a message below, see of metropolis reply. My ability is limited, so I can’t guarantee that what I write is right. But what I write is only after I have consulted a lot of information and understood to a certain extent. Therefore, I still have reference value and hope to communicate with you.

\