A: a cookie

Cookies are intended to interact with the server and exist as part of the HTTP specification

Understand the cookie

  1. To represent a unique cookie value: name, domain, path

  2. A cookie is just a small text file

  3. Although cookies are stored on the browser side, they are typically set on the server side.

  4. You can Set set-cookie in the HTTP return body to tell the browser what Cookie to store.

  5. Used to hold the request information of the client browser request server page

Cookie related fields

  1. Name: The name of a uniquely identified cookie. Cookie names are case insensitive. The cookie name must be URL-encoded.

  2. Value: string value stored in cookie. The value must be URL-encoded.

  3. Domain: The domain for which the cookie is valid. This cookie information is included in all requests sent to the domain. If not explicitly set, the field is considered to be from the field where the cookie was set.

  4. Path: Cookies should be sent to the server for that path in the specified domain. For example, you can specify the cookie can only access from http://www.wrox.com/books/, the http://www.wrox.com page won’t send a cookie information, even if the request is from the same domain.

  5. Expiration time: A timestamp indicating when the cookie should be deleted (that is, when it should stop sending this cookie to the server). By default, all cookies are deleted at the end of the browser session; But you can also set your own deletion time. This value is a DATE in GMT format (Wdy,DD-Mon-YYYY HH:MM:SSGMT) that specifies the exact time at which the cookie should be deleted. Therefore, cookies can remain on the user’s machine even after the browser is closed. If you set the expiration date to a previous time, the cookie will be deleted immediately.

  6. Security flag: When specified, cookies are sent to the server only when an SSL connection is used. For example, cookie information can only be sent to https://www.wrox.com, while requests from http://www.wrox.com cannot send cookies.

Application scenarios of cookies

  • In simple terms, a Cookie is information that the server temporarily stores on your computer (a.txt text file) so that the server can identify your computer. When you visit a Web site, the Web server sends a little file on your computer. Cookies record what you type or select on the site. The next time you visit the same site, the Web server will first look to see if it has the Cookie information left last time. If so, it will determine the user based on the content in the Cookie and send you a specific page content.

  • Websites can use cookies to track the habits of users to visit the website, such as when to visit, which pages to visit, the duration of each page, etc. Using this information, on the one hand, can provide personalized services for users, on the other hand, can also be used as a tool to understand all user behavior, for the improvement of website business strategy has certain reference value.

  • At present, the most widely used Cookie is to record user login information, so that the next access can not need to enter their own user name, password — of course, this convenience also exists the problem of user information leakage, especially when multiple users share a computer is prone to such problems.

Set/modify cookies

Cookie’s native API, which we need to encapsulate ourselves

// Direct copy document.cookie ='name=value; '/ / packagingset/ / Cookie methodsetCookie first encodes name and valuefunction setCookie(name,value,expires,path,domain,secure){

    var cookie = encodeURIComponent(name)+ '='+encodeURIComponent(value); // The following four parameters are optional, so useifJudge and appendif(expires){
        cookie +='; expires='+expires.toGMTString();
    }
    if(path){
        cookie += '; path='+path;
    }
    if(domain){
        cookie += '; domain='+domain;
    }
    if(secure){
        cookie += '; secure='+secure;
    }
    document.cookie = cookie;
}
Copy the code

Delete the cookie

The input parameters name, path, and domain uniquely identify cookies. If you set max-age to 0, the cookies can be deleted immediately.

function remove(name,domain,path){
    document.cookie = 'name='+name
                    +'; domain='+domain
                    +'; path='+path
                    +'; max-age=0';
}
Copy the code

Cookie shortcomings

  • Limits on the number and length of cookies. A maximum of 20 cookies can be stored in each domian in Internet explorer 6 or later, a maximum of 50 cookies can be stored in Internet explorer 7 or later, and a maximum of 50 cookies can be stored in Firefox. There is no hard limit for chrome and Safari. The length of each cookie cannot exceed 4KB, or it will be truncated.

  • IE and Opera will clean the least recently used cookies, Firefox will randomly clean cookies. This results in an inability to store information permanently.

  • Security issues. If the cookie is intercepted, that person can get all session information. Even encryption is useless, because the interceptor does not need to know the meaning of the cookie, as long as he forwards the cookie can achieve the goal.

  • And every time you request a new page, as long as the cookie meets the scope and function path, the cookie will be sent to the past, so that virtually waste bandwidth.

Two: local storage

Web Storage is designed to “store” data locally. Html5 Web Storage includes two Storage methods: sessionStorage and localStorage

LocalStorage && sessionStorage: as long as the expiration date and scope, the browser will load the Storage into memory every time it accesses.

  • LocalStorage localStorage for persistence, data will never expire unless actively deleted.

  • SessionStorage is used to store data in a session locally, which can only be accessed by pages in the same session and is destroyed when the session ends. Therefore, sessionStorage is not a persistent local storage, only session level storage. This means that as long as the browser window is not closed, the data will still exist even if the page is refreshed or another page is entered. SessionStorage is destroyed when the window is closed

  • LocalStorage is also restricted by the same origin policy.

  • LocalStorage and sessionStorage has the same operation method, such as setItem, the getItem, removeItem, methods of the clear, don’t like cookies need to encapsulate setCookie front-end developer himself, getCookie.

Three: the difference between



1. Differences between Cookie and session

  • Cookies are stored on the browser side and sessions are stored on the server side
  • Cookie security is weaker than session security. Someone can analyze cookies stored locally and cheat cookies. For security reasons, session security should be used.
  • Sessions are stored on the server for a certain amount of time. As the number of accesses increases, the resources of the server are consumed, so cookies can be used for server performance purposes
  • Cookie storage capacity is limited, a single cookie can not save more than 4K data, and many browsers limit a site to save a maximum of 20 cookies. For sessions, the default size is typically 1024K

2, cookie, sessionStorage, localStorage similarities and differences

Html5 webStorage contains sessionStorage and localStorage in common:

  • Both are saved in the browser and are of the same origin

The difference between:

  • Cookie data is always carried in same-origin HTTP requests, but webStorage does not carry it in requests and stores it locally
  • The storage size is different. Cookie is 4K, and webStorage can reach 5M or larger
  • Data validity time difference: sessionStorage is only session level storage. It only lasts until the current browser is closed. LocalStorage is always valid, even if the window or browser is closed, unless manually deleted by the user, it will become invalid. Cookies are valid only until the set cookie expiration time.
  • SessionStorage is not shared in different browser Windows, even on the same page. LocalStorage and cookies are shared across all origin Windows
  • The Web Storage supports the event notification mechanism to notify listeners of data updates. The API interface of Web Storage is easier to use.

3, The difference between Web storage and cookie

The concept of Web Storage is similar to cookie, except that it is designed for larger Storage capacity. Cookie size is limited, and every time you request a new page when the Cookie will be sent in the past, so virtually waste bandwidth, in addition to Cookie also need to specify scope, can not be called across the domain.

In addition, Web Storage with setItem, the getItem, removeItem, methods of the clear, don’t like cookies need encapsulation setCookie front-end developer himself, getCookie.

But Cookie is also not possible or missing: the role of Cookie is to interact with the server, as part of the HTTP specification exists, and Web Storage is only in order to “store” data in the local.

Cookies: both server and client can access; It’s only about 4KB in size; Has a validity period, will be deleted after the expiration;

Local storage: Only the local browser can access the data, the server cannot access the local storage until it is deliberately sent to the server through a POST or GET channel. 5MB per domain; There is no expiration data, it will remain until the user removes it from the browser or removes it using Javascript code.