JavaScript Local Storage Summary

Source: Internet
Author: User
Tags session id setcookie sqlite sessionstorage

Transferred from: https://i.cnblogs.com/EditPosts.aspx?opt=1

The following is the original text:

1. Simple comparison of various storage schemes
    • Cookies: Browser support, 4KB capacity
    • UserData: IE support only, capacity is 64KB
    • FLASH:100KB, non-HTML native, plug-in support required
    • Google Gears SQLite: Plug-in support required, unlimited capacity
    • LOCALSTORAGE:HTML5 with a capacity of 5M
    • SESSTIONSTORAGE:HTML5 with a capacity of 5M
    • Globalstorage:firefox is unique, Firefox13 no longer supports this method at first.

      UserData only IE support, Google Gears SQLite need plug-ins, Flash has been accompanied by the emergence of HTML5 gradually withdrew from the historical stage, so today we have only three of their protagonist: Cookie , LocalStorge SesstionStorge ;

2. Cookies

As a front-end and cookie will certainly not be less, the cookie is a relatively old technology
In 1993, Netscape employee Lou Montulli invented the widely used Cookie today in order to allow users to further improve their access to a website and to further implement a personalized network.

2.1 Characteristics of Cookies

Let's take a look at the characteristics of cookies:

    • 1) The size of the cookie is limited, the cookie size is limited to 4KB, and cannot accept big data such as large files or mail.

    • 2) Whenever a request involves cookie,cookie, it will be sent back and forth between the server and the browser (this explains why the local file cannot test the cookie). and cookie data is always carried in the same-origin HTTP requests (even if not required), which is also an important reason why cookies are not too large. Orthodox cookie distribution is implemented by extending the HTTP protocol, and the server prompts the browser to generate the appropriate cookie by adding a special line of instructions to the HTTP response header.

    • 3) Every time the user requests the server data, the cookie will be sent to the server with these requests, the server scripting language such as PHP can handle the data sent by the cookie, it is very convenient to say. Of course, the front-end is also able to generate cookies, with JS on the operation of the cookie is quite cumbersome, the browser only provides document.cookie such an object, the value of the cookie assignment, access is more troublesome. In PHP, we can use Setcookie () to set cookies, and $_cookie this hyper-global array to get cookies.

The contents of the cookie mainly include: name, value, expiration time, path and domain. The path together with the domain constitutes the scope of the cookie. If you do not set an expiration time, the cookie will be closed for the duration of the browser session. This cookie, which is the lifetime of the browser session, is referred to as a session cookie. Session cookies are generally not stored on the hard disk but are kept in memory, although this behavior is not regulated. If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and the cookies remain valid until the set expiration time expires. Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different ways of handling them.

2.2 Session

When it comes to cookies, you can't say a session.

Session mechanism. The session mechanism is a server-side mechanism that uses a hash-like structure (or perhaps a hash table) to hold information. When a program needs to create a session for a client's request, the server first checks to see if the client's request contains a session ID (called the session ID.), and if it is included, it has previously created a session for this client. The server will follow the session ID to retrieve the session (not retrieved, a new one), if the client request does not include session ID, then create a session for this client and generate a session ID associated with this session, The value of session ID should be a string that is neither duplicated nor easy to be found, and the session ID will be returned to the client in this response to save. This session ID can be saved by using a cookie so that the browser can automatically send the tag to the server in the interactive process. Generally the name of this cookie is similar to Seeesionid. However, a cookie can be artificially banned, and there must be other mechanisms that can still pass the session ID back to the server when the cookie is banned. A technique that is often used is called URL rewriting, which attaches the session ID directly behind the URL path. For example: http://damonare.cn?sessionid=123456 There is also a technique called form hidden fields. Is that the server automatically modifies the form, adding a hidden field so that the session ID can be passed back to the server when the form is submitted. Like what:

1234 <form name= "testform" action="/xxx" > <input type="hidden" name="SessionID" value= "123456" > <input type="text" >< /form>

In fact, this technique can be replaced simply by applying URL rewriting to the action.

2.3 Cookie and Session simple comparison

The difference between a cookie and a session:

    • 1) The cookie data is stored on the client's browser and the session data is placed on the server.

    • 2) Cookies are not very secure and others can analyze cookies stored locally and make cookie spoofing, taking into account that security should use the session.

    • 3) session will be saved on the server for a certain period of time. When the increase in access, will be compared to the performance of your server to reduce the performance of the server, you should use cookies.

    • 4) A single cookie cannot hold more than 4K of data, and many browsers limit a maximum of 20 cookies per site.
    • 5) so suggest:
      • Storing important information such as login information as session
      • Additional information can be placed in a cookie if it needs to be retained
2.4 Properties of Document.cookie

Expires property

The lifetime of the coolie is specified, and Coolie is temporarily present by default, and the values they store exist only during the browser session, and the values are lost when the user launches the browser, and if you want the cookie to exist for a period of time, set the Expires property to a future expiration date. Now replaced by the Max-age attribute, Max-age sets the lifetime of the cookie in seconds.

Path property

It specifies a Web page that is associated with a cookie. By default, the cookie is associated with the page that created it, the page in the same directory, and the page in the subdirectory under which the page is located.

Domain Property

The Domain property enables multiple Web servers to share cookies. The default value of the domain property is the host name of the server on which the cookie was created. You cannot set the domain of a cookie to a domain outside the domain where the server resides. For example, let the server located in order.damonare.cn be able to read the cookie value set by catalog.damonare.cn. If the cookie created by the catalog.damonare.cn page sets its own path property to "/", set the domain property to ". Damonare.cn", This cookie can then be accessed by all Web pages located in catalog.damonare.cn and all pages located in orlders.damonare.cn, as well as pages located on other servers in the damonare.cn domain.

Secure property

It is a Boolean value that specifies how cookies are transmitted over the network, which is not secure by default and is transmitted over a normal HTTP connection

2.5 Cookie Combat

Here we use JavaScript to write a cookie, borrowing W3cschool's demo:

1234567891011121314151617181920212223242526272829 function GetCookie (c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf (c_name + "=") if (c_start!=-1) { C_start=c_start + c_name.length+1C_end=document.cookie.indexOf (";", C_start) if (c_end==-1) c_end=document.cookie.length return unescape (document.cookie.substring (c_start,c_end)) } }return ""; }function Setcookie (c_name,value,expiredays) { var exdate=new Date () Exdate.setdate (Exdate.getdate () +expiredays)document.cookie=c_name+ "=" +Escape (value) + ((expiredays==null)? "" : "; Expires= "+exdate.toutcstring ()) }function Checkcookie () { Username=getcookie (' username ') if (username!=null && username!="") {alert (' Welcome again ' +username+'! ')} else{Username=prompt (' Please enter your name: ', '"") if (username!=null && username!="") { Setcookie (' username ', username,355) } }}

Note that this defines the lifetime of the cookie, which is 355 days

3. Localstorage

This is a persistent way of storing data that will never expire if you do not clear it manually.
It is also the use of Key-value to store data, the underlying data interface is SQLite, according to the domain name of the data are saved to the corresponding database file. It can save larger data (IE8 on the 10mb,chrome is 5MB), while the saved data is no longer sent to the server, to avoid bandwidth waste.

3.1 Localstorage Property methods

The following table is some of the properties and methods of Localstorge

Property Method Description
Localstorage.length Get the number in storage
Localstorage.key (N) Gets the key value of the nth element pair in the storage (the first element is 0)
Localstorage.getitem (Key) Gets the value corresponding to the key value key
Localstorage.key Gets the value corresponding to the key value key
Localstorage.setitem (key, value) Add data, key value is key, value is
Localstorage.removeitem (Key) Remove the data with key value key
Localstorage.clear () Clear All data
Disadvantages of 3.2 localstorage
    • ①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
4. Sessionstorage

Similar to the session used on the server side, it is a conversation-level cache and the data is erased when the browser is closed. But a bit special is that its scope is the window level, that is, the sessionstorage data between different windows can not be shared. Method of use (exactly the same as Localstorage):

Property Method Description
Sessionstorage.length Get the number in storage
Sessionstorage.key (N) Gets the key value of the nth element pair in the storage (the first element is 0)
Sessionstorage.getitem (Key) Gets the value corresponding to the key value key
Sessionstorage.key Gets the value corresponding to the key value key
Sessionstorage.setitem (key, value) Add data, key value is key, value is
Sessionstorage.removeitem (Key) Remove the data with key value key
Sessionstorage.clear () Clear All data
5. The difference between Sessionstorage and localstorage
    • Sessionstorage is used to store data locally in a session, which can only be accessed by a page in the same session and destroyed when the session ends. So sessionstorage is not a persistent local store, only session-level storage. When the user closes the browser window, the data is immediately deleted.

    • Localstorage is used for persistent local storage, and the data is never expired unless the data is actively deleted. Data is still available after the second, second, or next year.

5.1 Testing

Sessionstorage:

123456 if (sessionstorage.pagecount) { sessionstorage.pagecount= number(sessionstorage.pagecount) +1;} else{ sessionstorage.pagecount=1;} Console.log ("Visits" + Sessionstorage.pagecount + "time (s)");

Test process: We enter the above code in the console to see the print results

The console first enters the code:

Close the window and the console enters the code again:

The so-called close window is destroyed, that is, close the window to reopen the input code output or the image above, that is, after closing the window Sessionstorage.pagecount is destroyed, unless the center of gravity is created. Or you can enter it from a history record before the relevant data exists. OK, let's look at the Localstorge performance again:

123456 if (localstorage.pagecount) { localstorage.pagecount= number(localstorage.pagecount) +1;} else{ localstorage.pagecount=1; } Console.log ("Visits" + Localstorage.pagecount + "time (s)");

The console first enters the code:

Close the window and the console enters the code again:

6. Differences between Web Storage and cookies

The concept of Web Storage (Localstorage and Sessionstorage) is similar to a cookie, except that it is designed for larger capacity storage. The size of the cookie is limited, and every time you request a new page, the cookie is sent past, which virtually wastes bandwidth, and the cookie needs to specify the scope and cannot be called across domains.

In addition, WEB storage has methods such as setitem,getitem,removeitem,clear, unlike cookies that require front-end developers to encapsulate Setcookie,getcookie themselves.

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

(go) JavaScript local Storage summary

Related Article

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.