Learn more about browser storage-from cookie to WebStorage, IndexedDB

Preface

With the development and evolution of mobile networks, our mobile phones can now run “web App” in addition to native app-it is ready to use and go when used up. An excellent WebApp can even have functions and experiences comparable to native apps. The excellent performance of WebApp is partly due to the improvement of browser storage technology. Cookie’s function of storing data has been difficult to meet the needs of development and has gradually been replaced by WebStorage and IndexedDB. This article will introduce the differences, advantages and disadvantages of these storage methods.

If you want to read more excellent articles, please stamp them fiercely.GitHub blog

Cookie

1. source of 1.Cookie

Cookie’s job is not to store locally, but to “maintain state.”.
Because ..The HTTP protocol is stateless. The HTTP protocol itself does not store the communication state between requests and responses.Generally speaking, the server does not know what the user did last time, which seriously hinders the realization of interactive Web applications. In a typical online shopping scene, users browse several pages and buy a box of biscuits and two bottles of drinks. At the end of checkout, due to the stateless nature of HTTP, the server did not know what the user had bought without additional means, so a Cookie was born. It is one of the “extra measures” to bypass the stateless nature of HTTP. The server can set or read the information contained in Cookies, thereby maintaining the state of the user’s session with the server.

We can understand a Cookie as a small text file stored in a browser, which is attached to an HTTP request and “flies” between the browser and the server. It can carry user information, and when the server checks Cookie, it can get the status of the client.

In the shopping scene just now, when the user purchases the first item, the server sends a Cookie to the user while sending the webpage, recording the information of that item. When a user visits another page, the browser will send a Cookie to the server, so the server knows what he bought before. Users continue to purchase beverages, and the server adds new product information to the original Cookie. At checkout, the server reads the Cookie sent.

2. What are Cookie and application scenarios

Cookie refers to the data (usually encrypted) stored on the user’s local terminal by some websites in order to identify the user. Cookie is generated by the server and maintained and stored by the client.. Cookie enables the server to know which client the request originates from and maintain the state of the client. For example, refresh after logging in, the request header will carry the SET-cookie in the response header when logging in. The Web server can also read the cookie value when receiving the request, and can judge and restore the information state of some users according to the content of the cookie value.

As shown in the above figure,Cookie exist as key-value pairs..

Typical application scenarios are:

  • Remember the password and log in automatically next time.
  • Shopping cart function.
  • Record user browsing data and recommend commodities (advertisements).

3.Cookie Principle and Generation Method

Cookie principle

When visiting the website for the first time, the browser sends out a request. After the server responds to the request, it will add a Set-Cookie option in the response header and put the cookie into the response request. When the browser sends out the request for the second time, it will send the Cookie information to the server through the Cookie request header. The server will identify the user. In addition, the expiration time, domain, path, validity period and applicable site of the Cookie can be specified as required.

Cookie are generated in two ways:

  • Generation method 1: set-cookie in http response header

We can specify the Cookie value to be stored by setting-cookie in the response header. By default, domain is set as the host name of the Cookie page, and we can also set the value of domain manually.

Set-Cookie: id=a3fWa;   Expires=Wed, 21 Oct 2018 07:28:00 GMT;  //You can specify a specific expiration time or expiration period (Max-Age)

When the expiration time of the Cookie is set, the set date and time are only related to the client, not the server.

  • Generation Method 2: In js, you can read and write cookies through document.cookie are displayed in the form of key-value pairs

For example, we can view the generated cookie in Chrome’s Application panel by entering the following three sentences in the Nugget Community console:

document.cookie="userName=hello"
document.cookie="gender=male"
document.cookie='age=20;  domain=.baidu.com'

From the above figure, we can conclude that:

The Domain identity specifies which domain names can accept Cookie.. If domain is not set, it is automatically bound to the current domain that executed the statement.
If set to. baidu.com “,all domain names ending in” baidu.com “can access the Cookie, so the third code stored Cookie value cannot be read in the Nugget community.

4.Cookie defects

  • Cookie are not large enough.

Cookie size is limited to 4KB, which is not enough for complex storage requirements. When the Cookie exceeds 4KB, it will be cut. In this way, Cookie can only be used to access a small amount of information. In addition, many browsers have a limit on the number of cookie on a site.

It should be noted here that each cookie of each browsername=valueThe value of is about 4k, so 4k is not shared by all cookie under a domain name, but is the size of a name.

  • Too many Cookie can cause huge performance waste.

Cookie follow domain names closely. All requests under the same domain name will carry Cookie. Let’s imagine, if we only request a picture or a CSS file at this moment, we also have to carry a Cookie to run around (the key is that the information stored in the Cookie is not needed), which is a waste of people and money. Although cookies are small, there can be many requests. With the superposition of requests, the overhead caused by such unnecessary cookies will be unimaginable.

Cookies are used to maintain user information, and all requests under domain will carry cookies, but for requests for static files, carrying cookie information is useless at all. At this time, it can be solved by separating the domain name of cdn (which stores static files) and the domain name of the master station.

  • Since Cookie in HTTP requests are delivered in clear text, security is a problem unless HTTPS is used.

5.Cookie and security

For cookie, we also need to pay attention to security.

HttpOnly does not support reading and writing. browsers do not allow scripts to operate document.cookie to change cookie.
Therefore, in order to avoid cross-domain scripting (XSS) attacks, cookies marked with HttpOnly cannot be accessed through JavaScript’s Document.cookie API. They should only be sent to the server. If the Cookie containing the server-side Session information does not want to be called by the client-side JavaScript script, then the HttpOnly flag should be set for it.

Set-Cookie: id=a3fWa;   Expires=Wed, 21 Oct 2015 07:28:00 GMT;   Secure;  HttpOnly

Cookie marked Secure should only be sent to the server through requests encrypted by HTTPS protocol. However, even if the Secure token is set, sensitive information should not be transmitted through cookies, because cookies have inherent insecurity, and the Secure token cannot provide real security.

In order to make up for the limitation of Cookie and let “professional people do professional things”, Web Storage appeared.

Web Storage, a localStorage solution, has been added to HTML5. It is divided into two categories: sessionStorage and Local Storage.. With WebStorage, cookie can only do what it should do-act as a channel for the client to interact with the server and maintain the client state.

Ii. LocalStorage

1. characteristics of 1.LocalStorage

  • The saved data exists for a long time. The next time you visit the website, the webpage can directly read the previously saved data.
  • The size is about 5M
  • It is only used at the client side and does not communicate with the server side.
  • Interface encapsulation is better

Based on the above characteristics, LocalStorage can be used as a browser’s local cache scheme to improve the rendering speed of the first screen of the web page (when returning according to the first request, some unchanged information is directly stored locally).

2. Store/Read Data

The data saved by localStorage exists in the form of “key value pair”. In other words, each item of data has a key name and corresponding value. All data are saved in text format.
The setItem method is used to store data. It accepts two parameters, the first is the key name and the second is the saved data.
localStorage.setItem("key","value");
The getItem method is used to read data. It has only one parameter, the key name.
var valueLocal = localStorage.getItem("key");

For specific steps, please look at the following example:

<script>
 if(window.localStorage){
 localStorage.setItem('name','world')
 localStorage.setItem(“gender','famale')
 }
 </script>
<body>
 <div id="name"></div>
 <div id="gender"></div>
 <script>
 var name=localStorage.getItem('name')
 var gender=localStorage.getItem('gender')
 document.getElementById('name').innerHTML=name
 document.getElementById('gender').innerHTML=gender
 </script>
 </body>

3. Use scenario

LocalStorage has no special restrictions on storage. In theory, any data storage task that Cookie is not competent for and can be accessed by a simple key-value pair can be entrusted to LocalStorage.

Let me give you an example. Considering that one of the characteristics of LocalStorage is persistence, sometimes we prefer to use it to store some stable resources. For example, e-commerce websites with rich image content will use it to store image strings in Base64 format:

Iii. sessionStorage

The data saved by sessionStorage is used for a session of the browser. When the session ends (usually the window closes), the data is cleared. What makes sessionStorage special is that,Even if two pages under the same domain name are not opened in the same browser window, their sessionStorage content cannot be shared.; LocalStorage is shared in all homologous windows; Cookie are also shared in all homologous windows. The properties and methods of SessionStorage are exactly the same as those of LocalStorage except for the length of the storage period.

1. characteristics of 1.sessionStorage

  • Session-level browser storage
  • The size is about 5M
  • It is only used at the client side and does not communicate with the server side.
  • Interface encapsulation is better

Based on the above characteristics, sessionStorage can effectively maintain the form information. For example, when refreshing, the form information will not be lost.

2. Use scenario

SessionStorage is more suitable for storing information about the life cycle and the session level it synchronizes. This information only applies to the current session. When you open a new session, it also needs to be updated or released accordingly. For example, the sessionStorage of microblog is mainly to store your browsing footprint of this session:

Lasturl corresponds to the URL address you last visited, which is real-time. When you switch the URL, it will be updated. When you close the page, it really makes no sense to keep it. Just let it go. It is perfectly appropriate to use sessionStorage to process such data.

3. the difference between 3.sessionStorage, localStorage and cookie.

  • Common ground: all of them are stored on the browser side and follow the same source policy.
  • The difference is that the life cycle and scope are different.

Scope: localStorage can read/modify the same copy of localStorage data as long as it is under the same protocol, the same host name and the same port. SessionStorage is a bit stricter than localStorage. besides the protocol, host name and port, it is also required to be under the same window (i.e. the tab page of the browser)


Lifecycle: localStorage is a persistent local storage. The data stored in it will never expire. The only way to make it disappear is to delete it manually. SessionStorage is temporary local storage. It is session level storage. When the session ends (the page is closed), the storage content is released.

Web Storage is a very simple thing from definition to use. It is stored in the form of key-value pairs. This pattern is somewhat similar to objects, but even objects are not-It can only store stringsIn order to get the object, we need to parse the string first.

After all, Web Storage is an extension of Cookie, which can only be used to store a small amount of simple data. When encountering large-scale and complex data, Web Storage is also helpless. This is when we need to know our ultimate big boss——IndexedDB!

Iv. IndexedDB

IndexedDB is a low-level API.For clients to store large amounts of structured data (including files and blobs). The API uses indexes to realize high-performance search of the data. IndexedDB is a non-relational database running on a browser. Since it is a database, it is not the level of 5M and 10 m. Theoretically, IndexedDB has no upper storage limit (generally not less than 250M). It can store not only character strings but also binary data.

1. characteristics of 1.IndexedDB

  • Key value pair storage.

IndexedDB internally uses an object store to store data. All types of data can be stored directly, including JavaScript objects. In the object warehouse, data is saved in the form of “key-value pairs”. Each data record has a corresponding primary key. The primary key is unique and cannot be duplicated, otherwise an error will be thrown.

  • Asynchronous

IndexedDB operations do not lock the browser, and users can still perform other operations, in contrast to LocalStorage, whose operations are synchronized. Asynchronous design is to prevent reading and writing large amounts of data and slow down the performance of web pages.

  • Support services.

IndexedDB supports transaction, which means that in a series of operation steps, if one step fails, the entire transaction is cancelled, the database rolls back to the state before the transaction occurred, and there is no case of overwriting only part of the data.

  • Homologous restriction

IndexedDB is restricted by homology, and each database should create its domain name. Web pages can only access databases under their own domain names, not cross-domain databases.

  • Large storage space

IndexedDB’s storage space is much larger than LocalStorage, generally not less than 250MB or even no upper limit.

  • Supports binary storage.

IndexedDB can store not only strings but also binary data (ArrayBuffer object and Blob object).

2. common operations of 2.IndexedDB

Most operations in IndexedDB are not the mode of calling methods and returning results, but the mode of request-response.

  • Create open IndexedDB —-window.indexedDB.open("testDB")

This instruction does not return a handle to a DB object, what we get is aIDBOpenDBRequestObject, and the DB object we want is in its result attribute

In addition to result, the IDBOpenDBRequest interface defines several important attributes:

Onerror: callback function handle for request failure

Onsuccess: callback function handle for successful request

Onupgradeneeded: Request Database Version Change Handle

<script>
 function openDB(name){
 Varrequest = window.indexeddb.open (name)//create IndexedDB
 request.onerror=function (e){
 console.log('open indexdb error')
 }
 request.onsuccess=function (e){
 MyDB.db=e.target.result// this is an IDBDatabase object and this is the IndexedDB object.
 Log (mydb.db)//the db instance can be obtained here.
 }
 }
 var myDB={
 name:'testDB',
 version:'1',
 db:null
 }
 openDB(myDB.name)
 </script>

The console gets an IDBDatabase object, which is the IndexedDB object.

  • Close IndexedDB—-indexdb.close()
function closeDB(db){
 db.close();
 }
  • Delete IndexedDB—-window.indexedDB.deleteDatabase(indexdb)
function deleteDB(name) {
 indexedDB.deleteDatabase(name)
 }

3. the difference between 3.WebStorage, cookie and IndexedDB


As can be seen from the above table, cookie are no longer recommended for storage. LocalStorage and sessionStorage can be used if there is no large data storage requirement. Use localStorage storage as much as possible for data that doesn’t change much, otherwise you can use sessionStorage storage for storage.

Summary

It is the emergence and development of browser storage and caching technologies that have brought infinite changes to our front-end applications. In recent years, there are many third-party libraries based on storage and caching technologies. In addition, PWA is an excellent Web application model. Summarize the following key points of this article:

  • Cookie’s job is not to store locally, but to “maintain state.”
  • Web Storage is a data storage mechanism specially provided by HTML5 for browser storage and does not communicate with the server side.
  • IndexedDB is used by clients to store large amounts of structured data

To recommend a useful BUG monitoring toolFundebug, welcome to try free!

Welcome to pay attention to the public number:Front end craftsmanWe witness your growth together!

High quality communication group wechat public accounts
2 1

Reference article