"JavaScript" Cookie and Web Storage

Source: Internet
Author: User
Tags browser cache sessionstorage

This piece of learning for a while, but today to see the interview, let's talk about the drawbacks of the cookie and the difference between Web storage and cookies, unexpectedly still do not know where to start, so, or to self-carefully comb it again.

support for offline Web application development is a key point of HTML5. offline Web applications are applications that can still run when the device is not online.

开发离线Web应用需要几个步骤:    1、确保应用知道设备能否上网,以便下一步执行正确的操作。可以使用HTML5定义的navigator.onLine属性来检测。    2、应用必须在离线的时候能够访问一定的资源(图像,js,css等),只有这样才能正常工作。    3、必须有一块本地空间用于保存数据,无论能否上网都不影响读写。

Here are two ways to store data: Cookies and Web Storage

1. Cookies

CookieRole I think we all know, this role is like when you go to the supermarket shopping, the first time you do a shopping card, this shopping card store some of your personal information, the next time you come to this supermarket chain, the supermarket will identify your shopping card, the next time directly shopping is good. In layman's terms, when a user accesses a server through the HTTP protocol, the server returns some Key/value key-value pairs to the client browser and adds some restrictions to the data, which is the next time the user accesses the server when the condition is met. The data is then fully returned to the server.

The cookie is originally used by the client to store session information, which requires the server to send a set-cookiehttp header to any HTTP request as part of the response. Cookies
Name, with value, the name and value must be URL-encoded at the time of transfer. The browser stores such session information, after which, by adding a cookie for each request
The HTTP header sends the information back to the server.

A cookie is bound to a specific domain name in nature, and when a cookie is set, it is included when a request is made to the domain name that created it, which ensures that the information stored in the cookie is intelligently accessible to the authorized recipient and not to other domains. Cookies can be set through the Document.cookie property .

Composition of cookies

How cookies are manipulated
varCookieutil = {get: function (name){        varCookieName =encodeURIComponent(name) +"=", Cookiestart = Document.cookie.indexOf (cookiename), Cookievalue =NULL, Cookieend;if(Cookiestart >-1) {cookieend = Document.cookie.indexOf (";", Cookiestart);if(Cookieend = =-1) {cookieend = Document.cookie.length; } Cookievalue =decodeuricomponent(document.cookie.substring (Cookiestart + cookiename.length, cookieend)); }returnCookievalue; }, set: function (name, value, expires, path, domain, secure) {        varCookietext =encodeURIComponent(name) +"="+encodeURIComponent(value);if(Expiresinstanceof Date) {Cookietext + ="; Expires= "+ expires.togmtstring (); }if(path) {Cookietext + ="; Path= "+ path; }if(domain) {Cookietext + ="; Domain= "+ domain; }if(secure) {Cookietext + ="; Secure ";    } document.cookie = Cookietext; }, Unset: function (name, path, domain, secure){         This. Set (Name,"",New Date(0), path, domain, secure); }};
Benefits of Cookies
    • Configurable expiration rules: Cookies can expire at the end of a browser session, or they can exist indefinitely on a client computer, depending on the expiration rules of the client.
    • No server resources are required: The Cookie is stored on the client and is read by the server after it is sent.
    • Simplicity: A Cookie is a lightweight, text-based structure that contains simple key-value pairs.
    • Data persistence: Although the duration of the cookie on the client computer depends on the cookie expiration and user intervention on the customer, the cookie is usually the longest duration of data retention on the client.
The drawbacks of cookies

Although cookies provide a convenient way to persist client data and share the burden of server storage, there are many limitations.

    • limits on the number and length of cookies: The total number of cookies per domain is limited, IE6 or earlier versions up to 20 COOKIE;IE7 and later versions can last 50; Firefox up to 50 Chrome and Safari do not have a hard limit. The length of the cookie is also limited and it is best to keep the cookie within 4095B. Otherwise it will be cut off.
    • Security Issues: The cookie transmits all the data that is to be saved through the HTTP protocol header from the client to the server, and then from the server back to the client, all the data is stored in the client's browser, so the cookie data can be accessed, if the cookie is intercepted by someone, That person can get all the information. Even if encryption is not a problem, because the interceptor does not need to know the meaning of the cookie, he can only forward the cookie as it is to achieve the purpose.
    • performance issues: because all cookies are sent by the browser as request hair, storing a large amount of information in a cookie can affect the request performance of a particular domain
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 考虑到安全应当使用session .
    3. The session will be saved on the server for a certain amount of time. When the number of accesses increases, the performance of your server will be more expensive. 考虑到减轻服务器性能方面,应当使用cookie.
    4. A single cookie cannot hold more than 4K of data, and many browsers limit a maximum of 20 cookies per site.

      所以个人建议: 将登陆信息等重要信息存放为session, 其他信息如果需要保留,可以放在cookie中

2. Web Storage

The purpose of Web Storage is to overcome some of the limitations imposed by cookies, and when data needs to be tightly controlled at the client, there is no need to continually send data back to the server. Its main purpose is to:

    1. Provides a way to store session data outside of a cookie;
    2. Provides a mechanism for storing large amounts of data that can exist across sessions.
Storage type

The storage type provides maximum storage space (varies by browser) to store name-value pairs. It can only store strings, and non-string data is converted to strings before being stored.
Method:

clear();//删除所有值,Firefox未实现;getItem(name);//根据指定的name获取对应的值key(index);//获得index位置处的值的名字removeItem(name);//删除由name指定的名值对setItem(name,value);//为指定的name设置value值
Sessionstorage Object

Stores data specific to a session, which remains only until the browser is closed.
The data stored in the Sessionstorage can exist across the page refresh;
The Sessionstorage object is primarily used for storage of small pieces of data that are only for sessions. So no detailed introduction

Globalstorage Object

Purpose: stores data across sessions. To use the Globalstorage object, you first specify which fields can access the data, which is implemented by the square bracket tag:

//保存数据globalStorage["wrox.com""Vicky";//获取数据var name = globalStorage["wrox.com"].name;

It is preferable to specify the domain name when using the Globalstorage object, and it is safer to use Location.host as the property name if the domain name cannot be determined beforehand.

If you do not use RemoveItem () or delete delete, or if the user does not clear the browser cache, the data stored in the Globalstorage attribute will remain on the disk. Globalstorage is therefore ideal for storing documents on clients or for long-term saving of user preferences.

Localstorage Object

The Localstorage object is a scheme for persisting client data that supersedes Globalstorage in HTML5. To access the same Localstorage object, the page must be from the same domain name, using the same protocol, on the same port. This is equivalent to Globalstorage[location.host].
Save data in Localstorage and Globalstorage, data is retained to be deleted via JavaScript or the user clears the browser cache

//client data storage, a scheme for persisting client data, For long-term save user preferences!  function   Getlocalstorage   ()  { if  (typeof  localstorage = =  "object" ) {return  localstorage; } else  if  (typeof  Globalstorage = =  "object" ) {return  glob    Alstorage; } else  {throw  new< /span> error  ( "Local storage not Available" )}}< /code> 

To summarize:

In the higher version of the browser, JS provides the sessionStorage and globalStorage . Provided in the HTML5 localStorage to replace the globalstorage.
The HTML5 Web Storage includes two ways of storing:sessionstorage and localstorage.
sessionStorageused 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.
localStoragefor persistent local storage, the data will never expire unless the data is actively deleted.

The difference between Web storage and cookies

1, the concept of WEB storage and cookie similar, the difference is 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.
2, in addition, the WEB storage has setitem,getitem,removeitem,clear and other methods, unlike a cookie requires the front-end developer to package Setcookie,getcookie.
3. But 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" data.

"JavaScript" Cookie and 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.