preface

In class two days ago, when the teacher was talking hard on the browser interface, he suddenly stopped talking. He silently opened the debug panel, selected Application, pointed to storage and drew a circle on it with the mouse. Then he laughed strangely and asked us kindly: Does anyone know the difference between cookies, localStorage, sessionStorage and IndexDB under storage?

Then the audience silence for two minutes, the teacher can not, a simple introduction, said this to remember, the factory interview test is very much. Then I was very confused function did not remember, just remember “Dachang test”, so I thought for two days or decided to write this article to consolidate their knowledge.

Positive start

Front-end storage mode

Storage class:

  • Web Storage: THE Storage method proposed in HTML 5 has a capacity of 5 M.

   localStorage

   sessionStorage

  • Cookie: A universally supported HTTP-based storage device with a capacity of only 4 KB

  • Database storage: IndexDB Web SQL

The cache class:

  • Cache Storage: it is proposed in the specification of Service Worker that it is generally used with Service Worker for offline Cache.
  • Application Cache: A caching method introduced in HTML5.1 that can be used to build offline applications.

Cookie’s little secret

Cookies are based on the HTTP specification and are used to identify users. In the early days of the Internet, browsers had no state maintenance, which led to a problem that the server did not know the state of the browser and could not determine whether it was the same browser. In this way, user login and shopping cart functions cannot be realized. Lou Montulli introduced it into the Web in 1994 and finally into the W3C specification RFC6265.

The browser stores text strings locally according to certain rules and carries them whenever the browser sends a request to the server. The server determines browser states such as login, order, skin based on the > string. The e server can identify different user messages based on different cookies.

Cookie composition:

  • Name (Name)
  • Value (Value)
  • Domain (Domain)
  • Path
  • Failure time (Expiers/ max-age)
  • Size (Size)
  • HTTP request (HttpOnly)
  • Secure

Tip: The domain, path, expiration time, and security are all instructions from the server to the browser. They are not sent to the server as requested, only name and value pairs.

Limitations of cookies:

  • If you set a Cookie expiration time, the Cookie automatically becomes invalid when it expires.
  • If no expiration time is set, the Cookie is session-level and disappears automatically when the browser closes.

Advantages and disadvantages of Cookies:

Advantages:

  1. Can control the expiration time, will not be permanent, there is a certain security guarantee.
  2. Extensible and shareable across domains.
  3. Encryption and secure Transmission technology (SSL) can reduce the possibility of Cookie cracking.
  4. High compatibility.

Disadvantages:

  1. There is a limit on the number and length of cookies. Each Cookie cannot exceed 4 KB in length, otherwise the excess portion will be truncated.
  2. The data in the request header is vulnerable to interception.

How cookies are generated:

  1. The server returns a set-cookie response header when the browser accesses the server. The Cookie is Set when the browser parses this response header

2. Use the JAVASCRIPT script of the browserdocument.cookie = 'name=monsterooo';

Browser access to the server carries the cookie process

Create a cookie

/** * 'name', cookie name * 'value', cookie value * {* expires: 7, // Cookie expires in days; Default value: session cookie, disable The browser cookie is invalid. * path: '/', // Path affected by cookie; If the value is '/', the cookie is available in the entire domain. Default value: page path where cookies are created. * domain: 'example.com', // define the domain where the cookie is valid. Default: the page domain in which the cookie is created. * Secure: false, // Define cookie security, default: false, set to true, cookies are not valid in HTTP, cookie transmission requires a secure protocol (HTTPS). * } */ $.cookie('name', 'value', { expires: 7, path: '/', domain: 'example.com', secure: false});Copy the code

Read the cookie

$.cookie('name'); // Name returns value if it exists, null if it does notCopy the code

Delete the cookie

$.removecookie ('name'); $.removecookie ('name'); // => true $.removeCookie('nothing'); // => false Note: When deleting cookies, you must pass the exact same path, domain, and security options used to set cookies, unless you rely on the default options. That is, if the path attribute or Secure attribute is set when setting the cookie, the cookie must be deleted with these attributes. Otherwise, the cookie cannot be deleted successfully. // This won't work! $.removeCookie('name'); // => false // This will work! $.removeCookie('name', { path: '/' }); // => trueCopy the code

Web Storage (localStorage and sessionStorage)

Causes:

  • Overcome some of the limitations of cookies while storing some data that needs to be strictly controlled on the client side and does not need to be sent to the server.
  • Provides an alternative way to store sessions in addition to cookies.
  • Provides a large storage space to store data across calls.

They are available as properties of the Window object, and can be accessed directly through window.localStorage and window.sessionStorage.

Note: Web Storage can only store strings. If you use Web Storage to store objects, Object objects will appear. You can use json.stringify and json.parse to resolve this problem.

Web Storage instance method:

  • Clear: Deletes all values
  • GetItem (name): Gets the value based on the key passed in.
  • Key (index): name of the key that obtains the corresponding index.
  • RemoveItem (name): Deletes the key-value pair corresponding to the key
  • SetItem (name, value): Sets a value for the specified name.

sessionStorage:

  • Same-origin policy: Different from cookies, sessionStorage has higher access restrictions. Only the domain with sessionStorage configured can access sessionStorage.
  • Single TAB: Two tabs in the same domain cannot communicate with each other.
  • In the closed TAB page or under the new TAB page can not access the written sessionStorage, refresh the TAB page can still access the sessionStorage.

Usage Scenarios:

  1. It mainly stores small data at the session level.
  2. Store information that still needs to be stored when the page is refreshed, but does not need to be left behind when the page is closed.
  3. It is suitable for single page application and can be used to store login state information.

LocalStorage:

  • Same-origin policy: Same as sessionStorage, access to the same localStorage page must be from the same domain name, same protocol, and same port.
  • After localStorage is set, refresh or re-open the TAB page. Close the browser and re-open the original TAB page.

Scenarios used:

  1. Client data is persisted and can only be deleted by JavaScript or the user clears the browser cache.
  2. If there is a bit of a large amount of data, such as editor autosave, etc.
  3. Accessing common data across multiple pages. SessionStorage can only be used for one TAB page, while localStorage can be shared between multiple tabs.

SessionStorage localStorage

  • Life cycle: localStorage is a localStorage. It has no expiration date and can only be deleted by users themselves. SessionStroage is session storage, data is lost when the page is closed.
  • SessionStorage has a single-tab limit, but localStorage does not.

Storage:

Any operation we perform on the Storage object will trigger a Storage event on the document. The event object for this event has the following properties:

  • Domain: domain name of the changed storage space.
  • Key: indicates the name of the key to be set or deleted
  • NewValue: if it is a set value, it is a newValue. Null if it is a delete key.
  • OldValue: The value before the key was changed.

IndexDB with Web SQL

Features:

  • Access: Like Web SQL and Web Storage, indexDB can only be accessed under the domain name of the database.
  • Storage time: The storage time is permanent, unless the user clears the data, it can be used for long-term storage.
  • Size limits: There are no mandatory limits. However, indexDB will pop up a box in the browser for you to confirm when data exceeds 50 megabytes.
  • Performance: indexDB queries are relatively slow, while Web SQL is relatively fast.

IndexDB features:

  • Its data is stored in object storage space.
  • To create an object storage space, first define a key and then add data.
  • You can use a cursor query.

Cache Storage and Application Cache

The Cache Storage:

Cache Storage is used to store Response objects, that is, to Cache HTTP responses. A Cache Storage is a collection of multiple caches. Each Cache can store multiple response objects. It’s based on Promise.

The Application Cache:

It is a new application coarsening technology introduced in HTML5, and its emergence means that Web applications can be cached, run without a network, and build offline applications.

Advantages:

  • Offline browsing
  • Improved page loading speed
  • Reduce server stress

Transfer: blog.csdn.net/weixin_4401…