H5 Local Storage Web Storage

Source: Internet
Author: User
Tags sessionstorage

one, local storage background of Origin

  Due to the limitations of the size, format, and format of the data stored in the HTML4 era, Web applications can only use cookies if they want to store part of the user's information on the browser side. However, these limitations of the cookie also result in simple data such as identifiers such as IDs, which can only be stored by cookies.

 The following are restrictions on cookies:

Most browsers support a maximum of 4096 bytes of cookies.

The browser also restricts the number of cookies that the site can store on the user's computer. Most browsers allow only 20 cookies per site, and if you try to store more cookies, the oldest cookie is discarded.

Some browsers also impose an absolute limit on the total number of cookies they will accept from all sites, typically 300.
Cookies are sent to the backend server with HTTP requests by default, but not all requests require cookies, such as JS, CSS, pictures, and so on.
In order to solve a series of restrictions on cookies, HTML5 through the new API JS can directly store a large number of data to the client browser, but also support the complex local database, so that JS more efficient. HTML5 supports two types of webstorage:

Persistent local Storage (localstorage)
Session-level local storage (sessionstorage)

Ii. Classification of local storage

  H5 Local Storage has two APIs, one is Web Storage, and one is Web SQL. Whichever it is, it's all based on the JavaScript language, and I'll teach you how to use the Web Storage

Third, Web Storage

HTML5 defines the local storage specification Web Storage, which provides two types of storage api:sessionstorage and Localstorage, the difference between the length of time the data is saved and how the data is shared.

  1.localStorage is stored locally, the data store is persistent, unless the user or program deletes it, and the data stored by the Localstorage object has no time limit. Data is still available after the second, second, or next year.

  Features: ① security, permanent storage within the domain. That is, all pages from the same domain name in the client or browser can access the Localstorage data and the data is persisted in addition to deletion, but the data between the client or browser is independent of each other.

      data is not sent to the backend server with HTTP requests;

      The size of the data storage opportunity is not considered, because the HTML5 standard requires the browser to support at least 4MB.

See an example:

+

The code is as follows:

functionClickCounter () {if(typeof(Storage)!== "undefined"){                if(localstorage.clickcount) {Localstorage.clickcount=number (Localstorage.clickcount) +1; }Else{Localstorage.clickcount=1; } document.getElementById ("Result"). Innerhtml= "You have clicked the button" + Localstorage.clickcount + "Times"; }Else{document.getElementById ("Result"). Innerhtml= "Sorry, your browser does not support Web storage. "; }        }                                    </script> <p><button onclick= "ClickCounter ()" type= "button" > Point me! </button></p> <div id= "Result" ></div> <p> click the button to see an increase in the counter. </p> <p> Close the Browser tab (or window), reopen the page, and the counter will continue to count (not reset). </p>

2.sessionStorage is valid during the session, the data is automatically deleted after the browser is closed;

  Features: session control, short-term preservation. The session concept is similar to the server-side session concept, where short-term preservation refers to the automatic elimination of data after a window or browser or client shuts down.  

Compatibility

Note: IE9 Localstorage does not support local files, it needs to be the project to the server, to support!

Currently, all major browsers support HTML5 's Web storage features to some extent. As can be seen, basically all modern browsers have supported Web Storage.

Both the Android platform and the IOS platform's respective browsers basically support the Web Storage local storage feature. Mobile devices on the market today, in addition to Android phones and iphone phones, more and more tablet computers are available, and basically rely on two kinds of platforms. Using the Web Storage on the mobile side we hardly need to consider whether the browser is supported, of course, from the rigor of the code, it is advisable to check whether the browser supports it before use

Here are the detection methods:

 if   (window.localstorage) { 
   
    // 
     browser support Localstorage }
    else  
    { 
    // 
     }  if   (window.sessionstorage) { //  browser support Sessionstorage }else
      { //  } 
   
not supported

Third,localstorage   

The localstorage in the HTML5 local storage API is the same as sessionstorage in the usage method, except that Sessionstorage is emptied after the page is closed, and Localstorage is saved. Here we take localstorage as an example, briefly introduce the local storage of the next HTML5, and give some sample explanations for common problems such as traversal. Localstorage is the Html5 locally stored API that accesses data using key-value pairs, and only the data that is accessed is a string. Different browsers differ on the API support, such as how to use it, maximum storage space, and so on.

Storage: The string is stored as a key-value pair (key-value).

Main applications:   Shopping cart, customer login, Game archive ...

  data types that can be stored: arrays, images, JSON, styles, scripts ... (only content that can be serialized into strings can be stored)

  Storage Address: C:\Users\15014\AppData\Local\Google\Chrome\User data\default\local Storage (different computer, need to open the hidden file display, But in the C drive search Localstorage can find this folder. )

   Localstorage provides four ways to assist us in the operation of local storage.

  (1) Localstorage.setitem (key name, key value) stores a string type of data in the local client, where the first parameter "key Name" represents the identifier of the data, and the second parameter "key value" is the data itself. Such as:

        Localstorage.setitem ("name", "Zhang San");      // stores the data with the key name of name and the key value "Zhang San" to the local        Localstorage.setitem ("Age", "" ");        // data stored with a key named age and a key value of "28" to a local

  

(2) Localstorage.getitem (key name) reads the data stored locally, and reads the data of the corresponding key name as a parameter by key name. Such as:

    var data = Localstorage.getitem ("name");    alert (data); // Zhang San

(3) Localstorage.removeitem (key name) removes data that has been stored locally, and deletes the data for the corresponding key name as a parameter by key name. Such as:

    var data2 = Localstorage.removeitem ("name"); // removing data    from local storage with key name // undefined

(4) Localstorage.clear () removes all data from the local store. Such as:

    localstorage.clear () removes all data from the local store. such as:    localstorage.clear ()      ; // The key/value pairs of the saved "Age/28" and "name/Zhang San" are also removed, and all local data is Goodbye

(5) In addition, the four functions in sessionstorage are basically consistent with the function usage of the above localstorage classes, and they are no longer detailed.

Here is a small example:

<script type= "Text/javascript" >Localstorage.setitem ("Name", "Zhang San"); Localstorage.setitem ("Age", "28");   Verify (); //Verifying local StorageLocalstorage.removeitem ("name");   Verify (); //Verify if name existslocalstorage.clear ();   Verify (); //Verify that name and age are present                      //Custom validation functions to verify that the data for name and age exist            functionVerify () {varType = Localstorage.getitem ("name"); varPrice = Localstorage.getitem ("Age"); Type= type? Type: ' does not exist '; Price= Price? Price: ' does not exist '; Alert ("Name:" + type + "\ n" + "Age:" +Price ); }                          </script>

Third, localstorage expiration policy

Since HTML5 does not set an expiration policy for local storage, it is possible to write its own expiration policy program when processing the expiration policy of the data as follows:

<!DOCTYPE><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8" /><Metahttp-equiv= "Access-control-allow-origin"content= "Anonymous"><title>Locstorage Expiration Policy</title></Head><Body></Body></HTML><Script>functionSet (key,value) {varCurtime= NewDate (). GetTime ();//Get current TimeLocalstorage.setitem (key,json.stringify ({val:value,time:curtime}));//convert to JSON string sequence /*Description: Json.parse used to parse a JSON object from a string, such as var str = ' {' name ': ' Huangxiaojian ', ' age ': ' 23 '} ' Result: Json.parse (str) object  Age: "Huangxiaojian" Name: "__proto__": Object Note: Single quotes are written in {}, each property name must be in double quotation marks, or an exception will be thrown. Json.stringify () is used to parse a string from an object, such as var a = {A:1,b:2} result: Json.stringify (a) "{" A ": 1," B ": 2}"*/}functionget (KEY,EXP)//Exp is the set expiration time{  varVal=Localstorage.getitem (key);//gets the stored element  varDataobj=Json.parse (val);//parse out JSON objectif(NewDate (). GetTime ()-Dataobj.time>exp)//If the current time-minus the time that the stored element was set at creation times > Expiration Time{Console.log ("Expires");//Prompt Expires}Else{Console.log ("val="+dataobj.val);}}</Script>

Use the action as shown in:

H5 Local Storage Web Storage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.