With local storage, Web apps can store data locally in the user's browser.
Before HTML5, app data stores must use cookies, including requests from each server side, local storage is more secure, and can store large amounts of data locally without compromising the performance of the site.
Unlike cookies, the number of local storage stores is large (at least 5MB) and information is never transmitted to the server side.
Local storage is stored under the URL of the domain name and interface, and the same URL can be used to obtain information from each other.
Browser support
API |
Chrome |
Edge |
IE |
Firefox |
Safari |
Opera |
Web Storage |
4.0 |
12.0 |
8.0 |
3.5 |
4.0 |
11.5 |
HTML Local Storage Object
HTMNL Local Storage provides two objects for storing data in a client object:
- Window.localstorage-No expiration date for stored data
- Window.sessionstorage-store data (it also dies when the browser is closed)
Before using local storage, remember to use your browser to detect the compatibility of local storage:
if (typeof(Storage)!== "undefined") { // Code for localstorage/sessionstorage. Else { // sorry! No Web Storage support:}
The following will write Polyfill, which is actually using cookies to imitate local storage, at the bottom ~
Localstorage Object
Localstorage object is the time of the wood, even if you close the browser it has always existed, can be tomorrow, also or next week, or tomorrow to use
// StoreLocalstorage.setitem ("LastName", "Smith"); // Retrievedocument.getElementById ("result"). InnerHTML = Localstorage.getitem ("LastName");
Example Explanation:
- A key pair value was created for Localstorage: name= "LastName" and Value= "Smith"
- Gets the value of LastName in Localstorage and assigns it to the element with the ID of result.
The above example can also be written in the following style:
// Storelocalstorage.lastname = "Smith"; // Retrievedocument.getElementById ("result"). InnerHTML = Localstorage.lastname;
The syntax for removing items from "LastName" in Localsto is as follows:
Localstorage.removeitem ("LastName");
Method Summary
if(!localstorage.username) {Name=prompt ("What's your name?")); Localstorage.username=name; } console.log (localstorage["Username"]);Localstorage. SetItem ("X", 1);//Store a value in the name "X"Localstorage.GetItem("X");//Get Value //enumerate all stored name/value pairs for(vari=0;i<localstorage.length;i++) {//length indicates the total number of all name/value pairs varName=localstorage.Key(i);//get the first name, key when you do not know the key value of the use of the bar da! varValue=localstorage.getitem (name);//gets the value of the pair} localstorage. RemoveItem ("X");//Delete x ItemLocalstorage.Clear();//Delete all
Note: We can store any data type, but the key pair value is always stored in the form of a string (the browser only supports storing string types of data), so if you want to store and retrieve other types of data, remember to encode and decode the data :
1 /*2 * Benefits of comparison with cookies3 * 1. More storage space: each individual storage space under IE8 is 10M, other browsers are slightly different, but much larger than cookies. 4 5 2. Stored content is not sent to the server: When a cookie is set, the content of the cookie is sent along with the request, which is a waste of bandwidth for locally stored data. The data in the Web Storage is only present locally and does not interact with the server. 6 7 3. More rich and easy to use interface: WEB storage provides a richer set of interfaces, making data manipulation easier. 8 9 4. Separate storage space: each domain (including subdomains) has separate storage space, each storage space is completely independent, so it does not cause data confusion. Ten One However, cookies are also not available or missing: The role of cookies is to interact with the server as part of the HTTP specification, and the Web storage only for local "storage" of data A - ①cookie size limit is around 4k, not suitable for storage of business data - ②cookie Each time it is sent with an HTTP transaction, wasting bandwidth the - ①localstorage Size Limited to about 5 million characters, each browser inconsistent - ②localstorage not readable in privacy mode - ③localstorage Essence is in the read and write files, the number of data will compare cards (Firefox will be a one-time import data into memory, think it is scary AH) + ④localstorage can not be crawled by crawlers, do not use it to completely replace URL parameters - * */ - - //when a number is stored, it is automatically converted to a string - //However, when you get the value, don't forget to manually convert it to a numeric type inlocalstorage.x=10; - varx=parseint (localstorage.x); to //encode when a date type data is stored and decode when it is acquired +Localstorage.lastread= (NewDate ()). toUTCString (); - varLastread=NewDate (Date.parse (Localstorage.lastread)); the //using JSON can make it easy to encode basic data types *Localstorage.data=json.stringify (data); $ varData=Json.parse (localstorage.data);Panax Notoginseng
events that are triggered
//Storage event, the change of the key value is monitored setitem () trigger if(window.addeventlistener) { // Universal Browser window.addeventlistener ("Storage", Handle_ Storage,false); }Else if(window.attachevent) { ///IE browser window.attachevent (" Onstorage ", handle_storage); } //The properties of the storage event are: Key,newvalue,oldvalue,storagearea,url functionHandle_storage (e) {if(!e) e=window.event; Your handler Function! }
Sessionstorage Object
Sessionstorage objects are basically the same as localstorage objects, except for the life cycle: When a particular browser is closed, the data in the Sessionstorage is dead-cocked.
To emulate a local object in a low browser:
if(!window.localstorage) {window.localstorage={getItem:function(SKey) {if(!skey | |! This. hasOwnProperty (SKey)) {return NULL; } returnUnescape (Document.cookie.replace (NewRegExp ("(?: ^|. *;\\s*) "+ Escape (SKey). Replace (/[\-\.\+\*]/g," \\$& ") +" \\s*\\=\\s* ((?: [^;] (?!;)) *[^;]?). * ")," $ ")); }, Key:function(Nkeyid) {returnUnescape (Document.cookie.replace (/\s*\=) (?:. (?!;)) *$/, ""). Split (/\s*\= (?: [^;] (?!;)) *[^;]?;\ s*/) [Nkeyid]); }, SetItem:function(SKey, svalue) {if(!skey) {return; } Document.cookie= Escape (SKey) + "=" + Escape (svalue) + "; Expires=tue, 2038 03:14:07 GMT; path=/"; This. length = Document.cookie.match (/\=/g). length; }, Length:0, RemoveItem:function(SKey) {if(!skey | |! This. hasOwnProperty (SKey)) {return; } Document.cookie= Escape (SKey) + "=; Expires=thu, 1970 00:00:00 GMT; path=/"; This. length--; }, hasOwnProperty:function(SKey) {return(NewRegExp ("?: ^|;\ \s*) "+ Escape (SKey). Replace (/[\-\.\+\*]/g," \\$& ") +" \\s*\\= ") . Test (Document.cookie); } }; Window.localStorage.length= (Document.cookie.match (/\=/g) | |window.localstorage). Length;}
View Code
The following is a complex approach:
if(!window.localstorage) {window.localstorage={getItem:function(SKey) {if(!skey | |! This. hasOwnProperty (SKey)) {return NULL; } returnUnescape (Document.cookie.replace (NewRegExp ("(?: ^|. *;\\s*) "+ Escape (SKey). Replace (/[\-\.\+\*]/g," \\$& ") +" \\s*\\=\\s* ((?: [^;] (?!;)) *[^;]?). * ")," $ ")); }, Key:function(Nkeyid) {returnUnescape (Document.cookie.replace (/\s*\=) (?:. (?!;)) *$/, ""). Split (/\s*\= (?: [^;] (?!;)) *[^;]?;\ s*/) [Nkeyid]); }, SetItem:function(SKey, svalue) {if(!skey) {return; } Document.cookie= Escape (SKey) + "=" + Escape (svalue) + "; Expires=tue, 2038 03:14:07 GMT; path=/"; This. length = Document.cookie.match (/\=/g). length; }, Length:0, RemoveItem:function(SKey) {if(!skey | |! This. hasOwnProperty (SKey)) {return; } Document.cookie= Escape (SKey) + "=; Expires=thu, 1970 00:00:00 GMT; path=/"; This. length--; }, hasOwnProperty:function(SKey) {return(NewRegExp ("?: ^|;\ \s*) "+ Escape (SKey). Replace (/[\-\.\+\*]/g," \\$& ") +" \\s*\\= ") . Test (Document.cookie); } }; Window.localStorage.length= (Document.cookie.match (/\=/g) | |window.localstorage). Length;}
View Code
The above is actually manipulating cookies to simulate local storage, so the maximum data stored above is affected by cookies. The above code, used localStorage.getItem()
,, localStorage.setItem()
and localStorage.removeItem()
to get, set and delete keys is allowed, but the Localstorage.yourkey method to get the delete setting of a key is not allowed.
Of course, you can also manipulate cookies directly.
If you change the string to "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"
"; path=/"
(and change the name of the object), it becomes the sessionstorage Polyfill instead of the Lcoalstorage Polyfill. However, such an implementation would share the stored data across browsers (only when all the browsers in Windows are closed), but the data in the real sessionstorage can only be shared in the current browser environment.
Local Storage HTM5