Detailed web storage (cookie, sessionStorage, localStorage, indexedDB)

A, web storage concept Introduction

1. What is the web store?

It refers to the web storage web communication process by the client (e.g. browser) of the local storage for small amounts of data (Note: This is a broad web of said storage level instead of Web Storage). web storage types including old cookie, as well as the introduction of HTML5 sessionStorage, localStorage and indexedDB and so on.

web hosting environment is usually stored in the browser, with JavaScript interfaces provided by the browser, we can achieve these additions and deletions to change search data.

2. Why web store?

This is the oldest of cookie from the start.

Birth cookie stems from a contradiction: http protocol is stateless, there is a distinction between the server and the actual needs of different clients.

First understand stateless http protocol. Refers to a stateless, http protocol for any data transfers is no memory capacity. For example, if a client with your service sends a message, then approached the server sends another message, the server can not know these two messages from the same client.

The reason why you want to http protocol designed to stateless, because they want to maintain the connection status of all clients on the performance of the server's consumption of large, which can severely limit the ability of concurrent server. And in most cases, to maintain this status does not bring any benefits. So designers http protocol simply does not maintain state.

However, in many cases, the server must distinguish between different clients. Take Taobao it, upon receipt of an order request, the server must know which user the next one, which requires that it must know the current single login request and which previous requests from the same client (or the client each times must send a request to their account information and take all parameters).

To this end, the server design session (session) mechanism. After a user logs on, the server creates a session object for the user, storing parameters (such as user name, logon time, etc.) associated with the user, the object until the user logs out or login timeout will be destroyed. Each session object has a unique id, as long as the client is carried in the request is then sent on the id, the server can determine which user request is sent.

In this way, the client must have a mechanism to store the id's to ensure that can carry the id of each request before Log in. So, cookie was born.

When a user logs on, the server creates a session for the user (session) objects, then the server session object id parameter written response sent to the client. The client receives the response to the extracted parameter, stored in the browser. Each subsequent carries this id, according to this server id, which may determine that the request from the user at the time of transmission request. This particular field is used to store the id, called cookie (of course, cookie can store only id session, you can also store other parameters).

So, the basic role is to carry user ID cookie, to help the server distinguish different clients.

After the cookie types of memory: the reason sessionStorage, localStorage and indexedDB appear very simple: the more session data stored in the browser, you can reduce network traffic, improve site performance (although this cookie can also be used, but it individual capacity is only 4KB, it is not suitable for such purposes).

Two, web storage Detailed

1. cookie

Above we have the source of the cookie in detail, but here is to introduce cookie usage and features.

Cookie HTTP Cookie referred to, is transmitted in the HTTP request header Set-Cookie HTTP response as part of the string by the form name = value stored. After receiving the response to the distal end, it will be stored in a browser cookie, and carries the string each time a user request.

document.cookie cookie can be obtained at the front end, such as:

> document.cookie
< "_ga=77911531582348967; _gid=10966846041582958782"

Above the cookie stores a total of two parameters: _ga and _gid, two parameters separated by a semicolon and a space. encodeURIComponent cookie itself is encoded, and therefore, if the cookie contains Chinese, need to give the corresponding decoded value corresponding to decodeURIComponent.

In addition to the key and value, each parameter will also carry several other properties, including the domain, path, expiration time, safety signs, etc. These parameters can not be seen when using the document.cookie output, but can be viewed in the debug tool:
Here Insert Picture Description
meaning several parameters above are:

  1. key, key name.
  2. value, the key value.
  3. Domain, cookie domain, namely the domain of the site is located, it should be noted that, cookie domain is not case-port number.
  4. Path, cookie storage path, the default path is the root of the current project.
  5. Expires / Max-Age, cookie expiration time, in milliseconds. The default expire at the session fails when not set.
  6. Size, cookie size.
  7. HttpOnly, if only through the http request transmission. Some important cookie (such as sessionId), can only be set by the background and is not at liberty to modify, you can set this flag.
  8. Secure, safety signs. After setting the parameters, the cookie only in the https request will be carried.
  9. SameSite, in order to prevent CSRF attacks and track user and the new security properties, specifically refer to Ruan Yifeng: Cookie's SameSite property .

In general, cookie only to save the login information associated with, the most important is the server-side session id (session) objects. It is not suitable for storing large amounts of data, because the browser limits the size of each cookie can not exceed 4KB. In addition, the browser cookie is also the number of single domain under restrictions, the number varies depending on the browser, for developers, this number is generally not more than 20.

The default cookie will expire at the end of the session, you can manually modify max-ageor Expiresparameters to set the cookie expiration time, the former is defined cookie expire after how many seconds, while the latter is defined cookie fail at some point. If both these two parameters, the max-age higher priority.

Very simple to add parameters cookie:

document.cookie = "name=oeschger";
document.cookie = "favorite=tripe;max-age=120;path=/";
alert(document.cookie);
// 显示: name=oeschger; favorite=tripe

Note that although other parameters we set for the favorite is not printed out document.cookie, but they are still valid. The above example will fail when the session name server destruction, will be the favorite failed after 120 seconds.

Remove cookie does not provide direct interface parameters, it can be obtained by max-age the parameter is set to 0 or to set the current time Expires to invalidate immediately delete the cookie in order to achieve the object, such as:

document.cookie = "favorite=; max-age=0;";

This can be deleted from the favorite cookie.

cookie store as a client, there is a great advantage, influence end architecture is not service. We know that in a distributed architecture, session difficult to share between the various servers. The cookie is absolutely not an issue, it is stored in the client, it can be sent to any server.

At the same time, cookie there are a few obvious shortcomings. Is a security issue, cookie stored in the client's authentication information, if stolen, could produce unpredictable losses. Another problem mentioned above is the capacity, which is not so widely used web cookie store. In addition, cookie communication performance cost can not be ignored. Since all parameters of the cookie will be carried in each time you send a request to the backend, if the cookie is large, it will lead to every http request volume increases, affect the response speed of the site. In summary, cookie only to save a very small amount of user authentication information, and the need to ensure the cookie encryption policy transmission security.

2. sessionStorage和localStorage

Why introduce it put together in these two?

Because they are inherited from Storagethe principles of grammar and have a high similarity, that the Internet has introduced a large number of articles about the similarities and differences between the two. Let's look at their similarities:

(1) The same points

1. In principle, both of which are stored in the browser . The former is called "session storage," which is called "local storage." They are deployed on the window object, it can be accessed in the following ways:

window.localStorage
// 或者直接访问localStorage

window.sessionStorage
// 或者直接访问sessionStorage

2. Operation of both the syntax is the same (here to localStorage for example):

localStorage.setItem("name", "carter");  // 设置name: carter

localStorage.age = "24";   // 设置age: 24

localStorage.getItem("name");  // 获取name的值carter

localStorage.removeItem("name"); // 删除name

localStorage.clear();  // 清空localStorage

sessionStorage syntax above.

3. Both follow the same origin policy . That is the only store can be shared in the same domain, cross-domain can not access, so you can ensure the security of data.

4.localStorage sessionStorage and each have 5MB of storage space, and only store a string data type . For non-string type of data typically requires the use JSON.stringifymethod of compressing into a string, then the use of JSON.parseparsing.

(2) Different points

1. The time to failure are both different .
localStorage itself can not be fooled, even if the browser is closed, the next time you visit the site is still valid. localStorage does not provide a direct method to set the expiration time, we need to use a special strategy to periodically remove localStorage:

localStorage.setItem("name", JSON.stringify({
  value: "carter",
  time: (new Date()).getTime() // 保存时间戳
}))

function getItem(key, maxAge){
  let obj = localStorage.getItem(key);
  if(obj){  // 获取变量值对象
    obj = JSON.parse(obj);
  }
  // 存储时间小于最大生命周期时才读取该参数,否则将其清除
  if((new Date()).getTime() - obj.time < maxAge){
    return obj.value;
  } else {
    localStorage.removeItem(key);
    return "";
  }
}

getItem("name", 60 * 60 * 1000);  // 失效时间为1小时

In simple terms, is to save time localStorage together into storage, the value of time and then manually determine whether a timeout.

But sessionStorage session is bound to the page, a page when the session expires, the corresponding sessionStorage will be cleared. Note that, sessionStorage only will expire at the session page faults, that is to restore or refresh the page when the current page (eg click your browser's back button, or use your browser's page restore function) in some way, sessionStorage and will not fail, in other words, when a page is created sessionStorage, sessionStorage it always creates its perish.

2. The two different effective range .
Without cross-domain, localStorage across tabs to take effect, but sessionStorage only within the scope of the current tab.

This means that if you open a new one, the new page will be shared localStorage pages and the current page and the page with the current domain, but can not share sessionStorage. And if you open the current page in the iframe, and no cross-domain, and then localStorage sessionStorage can all be shared.

3. indexedDB

Although 5M space has been relatively large, but still can not meet all the front-end storage requirements.

This is because the front-end data cache to enhance the performance of the web site is huge (http it can effectively reduce the amount of data transmission, which is usually the most important factor leading to the site Caton), so more and more sites tend to front-end store more data. sessionStorage localStorage and can not meet this demand, because on the one hand, their capacity only 5M size; on the other hand, since the unstructured storage, when the large amount of data, they operate fast enough.

To this end, HTML5 specification launched a transactional database indexedDB front end. It can store large amounts of structured data, having read and write performance almost comparable backend database (of course, far from the functionality and capacity and back-end database).

IndexedDB probably need to use the following process:

  1. Open the database:
var request = window.indexedDB.open(databaseName, version);

So that you can open or create a new indexedDB database. When the incoming database name does not exist, it will create a new database, or they will open an existing database. When the database version number is omitted, if the database already exists, it defaults to the current version, or the version number 1.

  1. Event registration process

After calling the open method returns an IDBRequestobject, its registration error, successand upgradeneddedopen the resulting data of the event can be processed.

errorIt indicates that the database open failed:

request.onerror = function(err){
  console.log("数据库打开失败:" + err);
}

successIndicates that the database is opened successfully, then you can perform database read operation:

request.onsuccess = function (event) {
  let db = request.result;
  console.log('数据库打开成功');
};

upgradeneededRepresents the database needs to be upgraded, is different from the back-end database, indexedDB each modification of the contents of the database must upgrade the database version:

request.onupgradeneeded = function (event) {
  let db = event.target.result;
}

It should be noted that the new database itself related operations are classified as upgraded version of the database, hence the need for the upgradeneeded event:

request.onupgradeneeded = function (event) {
  db = event.target.result;
  var objectStore;
  if (!db.objectStoreNames.contains('person')) {
    objectStore = db.createObjectStore('person', { keyPath: 'id' });
  }
}
  1. Deletions change search operation execution data

Since the work had yet to use indexedDB, the lack of practical experience, and therefore temporarily detailed here. If you are interested, please refer Ruan Yifeng: Browser Database IndexedDB introductory tutorial .

The relationship between three front-end and back-end storage storage

We introduced above four categories of storage are all front-end storage, in addition to the cookie, the other three are directly accessed and manipulated by JavaScript.

Strictly speaking, in addition to the cookie, the other three types of storage are not absolutely necessary, then why do we need front-end store it?

The answer is to reduce the http data transmission, improve site performance.

To facilitate understanding, we put the whole process to access the site to make an analogy, it's like we go to the same school library. Library entire site itself, bookshelf is what we use back-end database, and the book is that all website data stored in a database on the shelves.

Library library management system is the background of the website service that provides office card, search, borrow, but also books and other services to users.

Like reading the front desk in the library, we can read their favorite books in the reading table. And we read the book, is the site provides us with a static page.

So how front-end cache to understand it?

It is like we are on the table reading the book to be read at hand. Imagine if we need to look ten books to the library, remove one on if every time we finished a review to re bookshelf, efficiency is obviously very low. This is the first time we will take over all ten books on the reading table. So for us, this ten fingertips on the desk of books is our front-end cache, they are so near us so we do not need to repeat the process ten times to find the book from the shelves.
Here Insert Picture Description
We make a further metaphor to understand the various types of storage.

Imagine, now the library has introduced a reservation system, each reader may want to make an appointment before coming to the library to the library access to books, the library will be able to advance these few books ready to be placed into a separate its reserved reservation area. Each reservation area is corresponding to the user session (session) object, which is stored in the server session.

So how do you know which library books are who scheduled it? Very simple, each reservation area corresponds to a person reading the card number, the card can be removed with reading the corresponding book reservation area, where your card is read cookie.

If you are a long-time user of the library, the library specifically for you reserved a reading area, you can always read their books on here, even if you leave, it will not clean up the library books. Available this long-term study area is localStorage.

If you are just an ordinary user, after the temporary library to find a piece of reading area. Then when you leave the library, the library will take you just borrow books from the school district to clean out. The next time you come to the library, you must re-borrow these books, this temporary school district is sessionStorage.

So what is indexedDB it? If someone needs to be held in the library a book club, numerous number of participants, involving different categories of books. In order to ensure that participants quickly to borrow books, the library decided to open a separate area to use all possible books all collated, and for the book club designed a small library management systems. Since some of the characteristics of book club, book placed in this region and management style different from the entire library (explain why the use of the back-end relational database, and front-end transactional database), so you can ensure the small amount of books lending higher efficiency in the case. So this opens up a separate area (including its subsidiaries library management system), is a front-end database indexedDB.

to sum up

Storage is one of the web browser provides developers with the most commonly used functions, basically has been completely replaced with a hidden form before temporarily storing data plan.

Wants to master all kinds of web storage, not only to learn their syntax, but also to pay attention to their life cycles, storage capacity, and other usage scenarios. With the front-end technology development and continuous improvement of front-end user experience requirements, the need for front-end storage site inevitably growing, so now is not commonly used indexedDB, in the future there may even be called a standard website. As a front-end developer, they should have a comprehensive understanding of, and more use at work, and more sum.

Published 44 original articles · won praise 98 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_41694291/article/details/104574835