Summary of local Javascript Storage

Source: Internet
Author: User
Tags sessionstorage
Summary: describes the differences and usage of cookies, LocalStorge, and SesstionStorge.

1. simple comparison of various storage solutions

Cookies: supported by browsers, with a capacity of 4 kb

UserData: only supported by IE, with a capacity of 64 KB

Flash: kb, non-HTML native, requires plug-in support

Google Gears SQLite: Support for plug-ins is required, with unlimited capacity

LocalStorage: HTML5, with a capacity of 5 MB

SesstionStorage: HTML5 with a capacity of 5 MB

GlobalStorage: exclusive to Firefox. This method is no longer supported since Firefox13.

UserData is only supported by IE, and Google Gears SQLite requires plug-ins. Flash has gradually exited the stage of history with the emergence of HTML5. So today we only have three of them: Cookie, LocalStorge, and SesstionStorge;

2. Cookie

As a front-end and Cookie, the number of times will certainly not be less. Cookie is an old technology. In 1993, the employees of Wangjing company Lou Montulli wanted users to access a website, in addition, to further improve access speed and further enable personalized networks, cookies are widely used today.

2.1 Cookie features

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

1) The cookie size is limited. The cookie size is limited to 4 kb and cannot accept big data like large files or emails.

2) as long as a request involves a cookie, the cookie will be sent back and forth between the server and the browser (this explains why the local file cannot test the cookie ). In addition, cookie data is always carried in the same source http Request (even if not required), which is also an important reason why Cookies cannot be too large. The orthodox cookie distribution is implemented by extending the HTTP protocol. The server prompts the browser to generate the corresponding cookie by adding a special line in the HTTP response header.

3) each time a user requests server data, the cookie will be sent to the server along with these requests. The server script language, such as PHP, can process the data sent by the cookie, which can be said to be very convenient. Of course, the front-end can also generate cookies. js operations on cookies are quite complicated. The browser only provides an object such as document. Cookie, which makes it troublesome to assign values to cookies. In PHP, we can set the cookie through setcookie () and get the COOKIE through the ultra-Global Array $ _ cookie.

Cookie content mainly includes: name, value, expiration time, path and domain. The path and the domain form the scope of the cookie. If no expiration time is set, it indicates that the cookie's life cycle is the browser session period. When the browser window is closed, the cookie disappears. This cookie is called a session cookie. Session cookies are generally stored in the memory instead of on the hard disk. Of course, this behavior is not standardized. If the expiration time is set, the browser will save the cookie to the hard disk, close it, and open the browser again. These cookies are still valid until the preset expiration time is exceeded. Cookies stored on hard disks can be shared among different browser processes, such as two IE Windows. For Cookies stored in the memory, different browsers have different processing methods.

2.2 Session

When it comes to cookies, you cannot ignore the Session.

Session mechanism. The session mechanism is a server-side mechanism. The server uses a structure similar to a hash (or a hash) to save information. When the program needs to create a session for a client request, the server first checks whether the client request contains a session id (called session id ), if it already exists, it indicates that a session has been created for this client. Then, the server retrieves and uses this session according to the session id (a new session will be created if it cannot be retrieved ), if the client request does not contain the session id, the client creates a session and generates a session id associated with the session. The session id value should be unique, the session id is returned to the client for saving in this response. The cookie can be used to save the session id, so that the browser can automatically send the id to the server according to the Rules during the interaction. Generally, the cookie name is similar to SEEESIONID. However, if a cookie can be artificially disabled, there must be other mechanisms so that the session id can still be passed back to the server when the cookie is disabled. A frequently used technology called URL rewriting is to directly append the session id to the end of the URL path. For example: http://damonare.cn? Sessionid = 123456 another technology is called form hidden fields. The server automatically modifies the form and adds a hidden field so that the session id can be passed back to the server when the form is submitted. For example:


In fact, this technology can be simply replaced by rewriting the URL of the action application.

2.3 simple comparison between Cookie and Session

Differences between Cookie and Session:

1) cookie data is stored in the client's browser, and session data is stored on the server.

2) Cookies are not very secure. Others can analyze the Cookies stored locally and perform cookie spoofing. session should be used for security reasons.

3) The session will be stored on the server for a certain period of time. When the number of access requests increases, it will occupy the performance of your server. To reduce the performance of your server, you should use cookies.

4) data stored in a single cookie cannot exceed 4 kb. Many browsers limit that a site can store up to 20 cookies.

5) we recommend that you:

Store important information such as login information as SESSION

Other information can be stored in the cookie if it needs to be retained.

2.4 document. cookie attributes

Expires attributes

Coolie lifetime is specified. By default, coolie exists temporarily, and their stored values only exist during browser sessions. These values are also lost when users launch browsers, if you want the cookie to exist for a period of time, you must set the expires attribute to an expiration date in the future. Now it has been replaced by the max-age attribute, and the max-age uses seconds to set the cookie survival time.

Path attribute

It specifies the webpage associated with the cookie. By default, the cookie is associated with the webpage that is created, the webpage in the same directory, and the webpage in the subdirectory in the directory where the webpage is located.

Domain attributes

The domain attribute allows multiple web servers to share cookies. The default value of the domain attribute is the host name of the server on which the cookie is created. You cannot set the domain of a cookie to a domain other than the domain of the server. For example, the server in order.damonare.cn can read the cookie value set by catalog.damonare.cn. If the cookie created on the catalog.damonare.cn page sets its path attribute to "/" and domain attribute to ".damonare.cn", then all webpages in catalog.damonare.cn and all webpages in orlders.damonare.cn, and webpages on other servers located in the damonare.cn domain can access this cookie.

Secure attributes

It is a Boolean value that specifies how cookies are transmitted over the network. By default, cookies are transmitted through a common http connection.

2.5 cookie practices

Here we use javascript to write a cookie and borrow the w3cschool demo:

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+1            c_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 the Cookie survival period is defined here, that is, 355 days.

3. localStorage

This is a persistent storage method, that is, if you do not manually clear the data, it will never expire.

It also uses the Key-Value Method to store data. The underlying data interface is sqlite, which saves data to the corresponding database files by domain name. It can save larger data (10 MB for IE8 and 5 MB for Chrome), and the stored data will not be sent to the server again to avoid bandwidth waste.

3.1 localStorage attributes

The following table lists the attributes and methods of localStorge.

5. Differences between sessionStorage and localStorage

SessionStorage is used to locally store data in a session. The data can be accessed only on pages in the same session. When the session ends, the data is also destroyed. SessionStorage is not a persistent local storage, but a session-level storage. When the user closes the browser window, the data is immediately deleted.

LocalStorage is used for persistent local storage. Unless data is actively deleted, the data will never expire. Data is still available on the second day, the second week, or after the next year.

5.1 Test

SessionStorage:

if (sessionStorage.pagecount){    sessionStorage.pagecount=Number(sessionStorage.pagecount) +1;}else{      sessionStorage.pagecount=1;}console.log("Visits "+ sessionStorage.pagecount + " time(s).");

Test process: Enter the preceding code on the console to view the printed result.

Enter the code for the first time in the console:

The so-called close window is destroyed. In this way, the close window is re-opened and the output result of the input code is as shown in the figure above. That is to say, sessionStorage. pagecount is destroyed after the window is closed, unless the center of gravity is created. Or the related data will exist only after the history record enters. Okay. Let's take a look at the localStorge performance:

if (localStorage.pagecount){    localStorage.pagecount=Number(localStorage.pagecount) +1;}else{    localStorage.pagecount=1; }console.log("Visits "+ localStorage.pagecount + " time(s).");

Enter the code for the first time in the console:

6. Differences between web Storage and cookie

The concept of Web Storage (localStorage and sessionStorage) is similar to that of cookie. The difference is that it is designed for larger Storage capacity. The Cookie size is limited, and the Cookie will be sent every time you request a new page. This will result in a waste of bandwidth. In addition, the cookie also needs to specify the scope, cross-origin calls are not allowed.

In addition, Web Storage has methods such as setItem, getItem, removeItem, and clear. Unlike cookies, front-end developers need to encapsulate setCookie and getCookie by themselves.

However, cookies are indispensable: cookies interact with servers and exist as part of HTTP specifications. Web Storage is only used to "Store" data locally.

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.