Form a view
features | cookie | localStorage | sessionStorage | indexDB |
---|---|---|---|---|
Data life cycle | Generally, it is generated by the server. You can set the expiration time. Front-end adoption and components such as JS-cookie can also be generated | It exists until it is cleaned up; Closed browsers are saved locally, but not across browsers | The clean refresh still exists when the page is closed, and cross-page interaction is not supported | Unless it’s cleaned up, it’s always there |
Data store size | 4K | 5M | 5M | Unlimited size |
Communicates with the server | It is carried in the header of the request each time and has an impact on the request performance. At the same time, because the request has, it is also prone to security problems | Don’t participate in | Don’t participate in | Don’t participate in |
The characteristics of | String key-value pairs store data locally | String key-value pairs store data locally | String key-value pairs store data locally | IndexedDB is a non-relational database (no SQL statement manipulation is supported). It can store large amounts of data, provide interfaces to query, and build indexes, all of which cannot be provided by other storage solutions. |
The browser can view data stored locally directly
The diagram below:
Cookies are not recommended for storing service data, because the request header carries cookies when the front-end interface requests them, wasting bandwidth resources and generally only storing login status information. For data that does not change much, try to use localStorage, otherwise use sessionStorage.
Note:
- HTML5 native storage can only store strings, any format of storage will be automatically converted to strings, so when reading, need to carry out their own type conversion.
- Note that the front-end storage is as asynchronous as the back-end database storage, meaning that fetching may not be ready.
Introduction:
Web Storage actually consists of two parts: sessionStorage and localStorage.
Benefits of Web Storage:
1. Reduce network traffic: After data is saved locally, data requests to the server are avoided, reducing unnecessary data requests, and reducing unnecessary data transfer between the browser and the server.
2. Fast display of data: good performance, read data from the local than through the network from the server to obtain data much faster, local data can be immediately available. Plus the web page itself can be cached, so the entire page and data can be displayed immediately if they are local.
-
More storage: IE8 has a single storage space of 10M. Other browsers implement it slightly differently, but much larger than cookies.
-
Stored content will not be sent to the server: When a Cookie is set, the content of the Cookie will be sent to the server along with the request, which is a waste of bandwidth for data stored locally. The data in Web Storage only exists locally and does not interact with the server.
-
More rich and easy to use interfaces: Web Storage provides a richer set of interfaces, making data operation more convenient (such as: getItem\setItem).
-
Independent storage space: Each domain (including subdomains) has independent storage space. Each storage space is completely independent, preventing data confusion.
localStorage
The size of a single localStorage is limited. You can use multiple iframes to use multiple domain names to overcome the maximum limit of data stored on a single page.
Special note: when multiple tabs of the browser open the same domain name, the localStorage content is generally shared. Its location can listen to the event “storage” for consistency operation response processing. This will lead to the following phenomena:
TAB page 1: Modify an attribute value in localStorage through a behavior, and then the data interface depends on the attribute value.
TAB page 2: The data on TAB page 2 is incorrect because the localStorage TAB pages are shared.
Localstorage.setitem ("type","1") // Causes the browser to store an attribute called type in its localStorage memory with a value of 1; Localstorage. getItem("type") // Get the corresponding property in localStorageCopy the code
sessionStorage
Similar to localStorage, but sessionStorage is automatically cleared when the browser closes.
SessionStorage, localStorage and cookie are all data stored in the browser side. Among them, the concept of sessionStorage is very special, introducing the concept of a “browser window”.
SessionStorage is data that is always present in the same window (or TAB) of the same origin. 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. SessionStorage objects are also different for different Windows opened independently, even for the same page.
Temporary storage: In many cases, data only needs to be used while the user is browsing a set of pages and then discarded after the window is closed. SessionStorage is very convenient in this case.
Method of use
/ / store window. The sessionStorage. SetItem (" token ", "adfasfasfasfd") / / remove sessionStroage the getItem (" mykey ") sessionStroage. Mykey / / remove sessionStroage. The clear ()Copy the code
Cookie
Cookie Data stored in a user’s browser for identification or Session tracking. Cookies are typically sent to the server through HTTP requests.
Cookie expiration configuration cookies are classified into Session cookies and persistent cookies. Cookie setting has an HttpOnly parameter, the front-end browser using document. Cookie is not able to read the HttpOnly type of Cookie, is set to HttpOnly Cookie records can only be sent to the server for reading and writing operations through HTTP request. In this way, the Cookie record of the server is avoided to be modified by the front-end javascript, and the security of the server to verify the Cookie is ensured.
The content of cookies mainly includes: name, value, expiration time, path and domain. The path and the domain together form the scope of the cookie. If the expiration time is not set, it indicates that the lifetime of the cookie is during the browser session. When the browser window is closed, the cookie disappears.
Cookies with a lifetime of a browser session are called session cookies. Session cookies are generally not stored on hard disk but in memory. If the expiration time is set, the browser saves cookies to hard disk, closes the browser and opens the browser again. These cookies remain valid until the expiration time is exceeded. Cookies stored on the hard disk can be shared between different browser processes, such as two IE Windows. Different browsers treat cookies stored in memory differently.
session
The session mechanism is a server-side mechanism that uses a hash table like structure (and possibly hash tables) to store information. When the program needs to create a session for a client request, the server first checks whether the client request contains a session identifier (called the session ID). If it does, it indicates that a session has been created for the client before. If the client request does not contain the session ID, a session is created for this client and a session ID associated with this session is generated. The value of the session ID should be a string that is neither duplicated nor easily found to be faked. The session ID will be returned to the client for storage in this response.
Other storage methods (Understanding)
WebSQL: 2d table formation stores large amounts of data to the client, but currently only Chrome has it.
IndexDB: A set of apis, similar to NoSQL, for storing large amounts of structured data on the client side and using indexes for high-performance retrieval of that data. Application Cache: a file caching mechanism that selectively stores static resource files such as javascript, CSS, and images locally through the manifest configuration file is obsolete.
CacheStorage: A Cache object defined in the ServiceWorker specification to hold each ServiceWorker declaration (covered separately in a future blog post), as a possible offline alternative to Application Cache.
Flash cache: Based on Flash, it can read and write the local directory of the browser.
SessionStorage, localStorage, and cookie comparison
Common: both are saved in the browser side, and the same origin. The difference between:
-
Whether to pass with the request
Cookie data is always carried (even if it is not needed) in same-origin HTTP requests, i.e. cookies are passed back and forth between the browser and the server. However, sessionStorage and localStorage do not automatically send data to the server and only store data locally. Cookie data also has the concept of path, which can restrict cookies to a specific path.
-
Storage size limits vary
Cookie data cannot exceed 4K, and because cookies are carried with each HTTP request, cookies are only good for holding small amounts of data, such as session identifiers. SessionStorage and localStorage, while also limited in size, are much larger than cookies, reaching 5M or more.
-
Different data validity periods
SessionStorage: only valid until the current browser window closes, naturally not persistent; LocalStorage: always valid, saved even when the window or browser is closed and therefore used as persistent data; But it’s only stored in the current browser, so if you switch browsers, the data will be saved when the other browser opens, because it’s stored in the browser; Cookies only remain valid until the set cookie expiration time, even if the window or browser is closed.
-
Different scope
SessionStorage is not shared across different browser Windows, even on the same page; LocalStorage is shared in all origin Windows; Cookies are also shared across all the same origin Windows.
Cookie and session comparison
The difference between:
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 cookies stored locally and cheat cookies
3. Sessions are stored on the server for a certain period of time. When the number of visits increases, it takes a lot of performance out of your server
4. The data saved by a single cookie cannot exceed 4K. Many browsers limit the maximum number of cookies saved by a site to 20.
5. Therefore, personal advice: Store important information such as login information as SESSION and other information. If it needs to be carried in each request, it can be stored in cookies and other localized cached data in Web Storage
Case code:
Const STORAGE_KEY = 'todo-vuejs'// Equivalent to the database name of this page export default {fetch:function(){// parse is used to parse json objects from a string. return JSON.parse(window.localStorage.getItem(STORAGE_KEY) || '[]') }, Save: function (items) {/ /. Stringify to from a parse a string object window. The localStorage. SetItem (STORAGE_KEY, JSON stringify (items)}, / * access to the array length * / getLength: function () {return JSON. Parse (window. LocalStorage. The getItem (STORAGE_KEY) | | '[]'). The length; }, /* Returns the value of the last key in the array. @ keyName need to get the value of key name * / getLastKey: function (keyName) {let arr = JSON. Parse (window. LocalStorage. The getItem (STORAGE_KEY) | | '[]'); for(let key in arr[arr.length-1]){ if(key == keyName){ return arr[arr.length-1][keyName] }else{ return 0; } } }, clear:function(){ window.localStorage.clear(); }}Copy the code