Introduction and use of browser local storage - localStorage

1. What is localStorage?

In HTML5, a new localStorage feature has been added. This feature is mainly used for local storage, which solves the problem of cookie bandwidth and insufficient storage space (the storage space of each cookie in cookie is 4k), the size of localStorage , the general browser supports 5M, but it will be different in different browsers.

Two, the advantages and disadvantages of localStorage

Advantage
1. localStorage breaks through the 4K limit of cookies.
2. localStorage can directly store the requested data locally, which is equivalent to a 5M front-end page database, which can save bandwidth compared to cookies.

Disadvantage
1. The size is different in different browsers, and IE browsers only support IE8 and above.
2. At present, all browsers will limit the value type of localStorage to string type, and some conversion is required to use JSON object type.
3. localStorage cannot be read under the privacy mode of the browser.
4. localStorage cannot be crawled by crawlers.

Related: The only difference between localStorage and sessionStorage is that localStorage belongs to permanent storage, while sessionStorage belongs to the session. When the session ends, the key-value pairs in sessionStorage will be cleared.

3. Support of localStorage by browsers

Browser support for localStorage

Fourth, the use of localStorage

Because localStorage is a new addition to HTML5, older browsers do not support it, so the first step in using localStorage is to check whether the current browser supports it.

if(!window.localStorage){
    
    
	alert("您的浏览器不支持localStorage!");
}else{
    
    
	//可以正常使用localStorage
}

localStorage stores data in the form of key-value. Its value is currently fixed as a String string. There are three forms of key-value usage, which are common for writing and reading.
1. localStorage["a"]
2. localStorage.a
3. localStorage.setItem("a", value)
So, we can use it like this:

if(!window.localStorage){
    
    
	alert("您的浏览器不支持localStorage!");
}else{
    
    
	//可以正常使用localStorage
	var localStorage = window.localStorage;
	//写入数据
	localStorage["a"] = "1";
	localStorage.b = "2";
	localStorage.setItem("c","3");
	//读取数据
	alert("a="+localStorage.getItem("a"));
	alert("b="+localStorage["b"]);
	alert("c="+localStorage.c);
}

Guess you like

Origin blog.csdn.net/babdpfi/article/details/105805250