preface

With the development and evolution of mobile networks, we now have “WebApps” on our phones in addition to native apps, which are ready to use and ready to go. A good WebApp can even have the same functionality and experience as a native App. WebApp’s superior performance is partly due to improvements in browser storage technology. The function of cookie to store data has been difficult to meet the needs of development, and has been gradually replaced by WebStorage and IndexedDB. This article will introduce the differences, advantages and disadvantages of these storage methods.

For more quality articles please clickMaking a blog

A, Cookie,

1. The source of the Cookie

The job of a Cookie is not to store it locally, but to “maintain state.” Because HTTP is stateless, the HTTP protocol itself does not store the state of communication between a request and a response. In layman’s terms, the server does not know what the user did last time, which seriously impedes the implementation of interactive Web applications. In a typical online shopping scenario, the user browses through several pages and buys a box of cookies and two drinks. At the end of the checkout, due to the stateless nature of HTTP, the server does not know what the user has bought without additional means, so cookies are born. It is one of the “extra tricks” used to bypass HTTP’s statelessness. Cookies can be set or read by the server to maintain state in the session between the user and the server.

We can think of a Cookie as a little text file stored in a browser, attached to an HTTP request, and “flying back and forth” between the browser and server. It can carry user information, and when the server checks the Cookie, it can get the status of the client.

In the shopping scenario, when the user selects the first item, the server sends the user a web page and a Cookie to record the information about the item. When a user visits another page, the browser sends a Cookie to the server, so the server knows what he purchased. As the user continues to buy a drink, the server appends new product information to the original Cookie. At checkout, the server reads the Cookie sent to it.

2. What are cookies and application scenarios

Cookies are data stored (usually encrypted) on a user’s local terminal by some web sites to identify the user. Cookies are generated by the server and maintained and stored by the client. Through cookies, the server can know which client the request comes from, so that the client state can be maintained. For example, after login, the request header will carry set-cookie in the response header during login, and the Web server can also read the value of cookie when receiving the request. The information state of some users can be judged and restored according to the content of cookie value.

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

Typical application scenarios include:

  • Remember the password for automatic login next time.

  • Shopping cart functionality.

  • Record user browsing data and recommend products (advertising).

3. Principle and generation method of Cookie

The principle of cookies

When visiting the website for the first time, the browser sends a request, and the server responds to the request, it will add a set-cookie option in the response header and put the Cookie in the response request. When the browser sends a 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, and the Cookie expiration time, domain, path, expiration date, and applicable site can be specified as required.

There are two main ways to generate cookies:

  • Generation method 1: set-cookie in HTTP Response header

We can specify the value of the Cookie to store via set-cookie in the response header. By default, domain is set to the hostname of the Cookie page, or we can manually set the value of domain.

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2018 07:28:00 GMT; // You can specify a specific Expires or max-age.Copy the code

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

  • Generation method 2: Js can read and write cookies through document.cookie, in the form of key-value pair display

For example, we can view the generated cookie in Chrome’s Application panel by typing the following three lines in the Nuggets Community Console:

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

It can be concluded from the above figure that:

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

4. The defects of the Cookie

  • A Cookie is not big enough

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

Note here: The value value of each cookie name=value of each browser is about 4K, so 4K is not shared by all cookies under a domain name, but the size of a name.

  • Too many cookies can be a huge performance waste

Cookies follow the domain name. All requests under the same domain name carry cookies. Imagine if we were just asking for an image or a CSS file at the moment, and we were also carrying around a Cookie (the key is that the information stored in the Cookie is not needed), how wasteful it would be. Although cookies are small, there can be many requests. As the requests pile up, the overhead of such unnecessary cookies will be unimaginable.

Cookie is used to maintain user information, and all requests under domain name (domain) will carry cookie, but for static file request, carry cookie information is useless, at this time can be solved by CDN (storage of static files) domain name and the domain name of the master site.

  • Because cookies in HTTP requests are passed in plain text, security is problematic unless HTTPS is used.

5. Cookies and security

In the case of cookies, we also need to pay attention to security.

HttpOnly does not support reading and writing. Browsers do not allow scripting to manipulate document.cookie to change cookies. Cookies with HttpOnly tags are not accessible through JavaScript’s Document.cookie API; they should only be sent to the server. If the Cookie that contains the server Session information does not want to be called by the client 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
Copy the code

Cookies marked Secure should only be sent to the server through requests that are encrypted by the HTTPS protocol. But even if Secure flags are set, sensitive information should not be transmitted through cookies because cookies are inherently insecure and Secure flags do not provide a guarantee of security.

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

HTML5 has added a localStorage solution —-Web Storage, which is divided into two categories: sessionStorage and localStorage. With WebStorage, cookies can do just what they’re supposed to do — act as a channel between the client and the server, keeping the client state.

Second, the LocalStorage

1. The characteristics of the LocalStorage

  • The saved data exists for a long time, and the next time you visit the site, the page can read the previously saved data directly.
  • The size is about 5M
  • It is used only on the client and does not communicate with the server
  • Good interface encapsulation

Based on the above features, LocalStorage can be used as a local cache solution of the browser to improve the speed of rendering the first screen of a web page (when the first request is returned, some invariant information is directly stored locally).

2. Save/read data

Data stored in localStorage is in key-value pairs. That is, each item of data has a key name and corresponding value. All data is stored in text format. The setItem method is used to store data. It takes two parameters, the first is the key name and the second is the saved data. localStorage.setItem(“key”,”value”); The data is read using the getItem method. It takes only one argument, the key name. var valueLocal = localStorage.getItem(“key”);

For details, see the following example:

<script>
if(window.localStorage){
  localStorage.setItem('name','world')
  localStorage.setItem('gender','female')
}
</script>
Copy the code
<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>
Copy the code

3. Application scenarios

LocalStorage has no special limitations on storage. In theory, it can do all the data storage tasks that cookies cannot do and can be accessed with simple key-value pairs.

Here is 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, image-rich e-commerce sites will use it to store Base64 image strings:

Third, sessionStorage

SessionStorage stores data for a session in the browser. When the session ends (usually when the window closes), the data is cleared. The special feature of sessionStorage 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 origin Windows; Cookies are also shared across all the same origin Windows. The properties and methods of SessionStorage are exactly the same as those of LocalStorage, except for the length of the retention period.

1. The characteristics of the sessionStorage

  • Session-level browser storage
  • The size is about 5M
  • It is used only on the client and does not communicate with the server
  • Good interface encapsulation

Based on the above features, sessionStorage can effectively maintain form information, such as refresh, form information is not lost.

2. Application scenarios

SessionStorage is more suitable for storing life-cycle and session-level information that it synchronizes. This information only applies to the current session and needs to be updated or released when you start a new session. For example, sessionStorage of Weibo is mainly used to store your browsing footprint of this session:

Lasturl corresponds to the lasturl you visited, which is immediate. It updates when you switch urls, and there’s really no point in keeping it when you close the page, just release it. SessionStorage is the best way to handle such data.

3. The difference between sessionStorage, localStorage and cookie

  • Common: Both are saved in the browser and comply with the same origin policy.
  • Difference: difference in life cycle and scope

Scope: As long as localStorage is in the same protocol, the same host name, the same port, can read/modify to the same localStorage data. SessionStorage is more stringent than localStorage. In addition to protocol, host name, port, sessionStorage also requires the same window (that is, the browser TAB)

Life cycle: localStorage is persistent localStorage, stored in the data is never expired, the only way to make it disappear is to manually delete; SessionStorage is temporary local storage, it is session level storage, when the session ends (the page is closed), the storage content is also released.

Web Storage is a very simple thing to define and use. It is stored as key-value pairs, which is a bit like an object but not even an object — it can only store strings, and to get an object we need to parse the string one more time.

Ultimately, Web Storage is an extension of cookies, which can only be used to store small amounts of simple data. When it comes to large, complex data, Web Storage can’t help. IndexedDB! IndexedDB! IndexedDB!

Four, with 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 enable a high-performance search of this data. IndexedDB is a non-relational database that runs on a browser. Since it is a database, it is not 5M, 10M, such a small level of play. Theoretically, IndexedDB has no storage upper limit (generally no less than 250MB). It can store binary data as well as strings.

1. With IndexedDB characteristics

  • Key-value pair storage.

IndexedDB uses an object Store internally to store data. All types of data can be stored directly, including JavaScript objects. In the object warehouse, data is stored as “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 does not lock the browser and users can still perform other operations, in contrast to LocalStorage, where operations are synchronous. Asynchronous design is designed to prevent massive data reads and writes from slowing down the performance of a web page.

  • Support transactions.

IndexedDB supports transaction, which means that if one of a series of steps fails, the entire transaction is cancelled and the database is rolled back to the state before the transaction occurred, without overwriting only a portion of the data.

  • The same-origin restrictions

IndexedDB is subject to the same origin restriction, with each database corresponding to the domain name that created it. Web pages can only access databases under their own domain names, but not cross-domain databases.

  • Large storage space

IndexedDB has much more storage space than LocalStorage, usually no less than 250MB or even no upper limit.

  • Binary storage is supported.

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

2. Common operations on IndexedDB

Most operations in IndexedDB are not in the usual call-method, result-return mode, but in the request-response mode.

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

Instead of returning a handle to a DB object, we get an IDBOpenDBRequest object, and the DB object we want is in its Result property

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

Onerror: Callback function handle for failed request

Onsuccess: Callback function handle to request success

Onupgradenneeded: Handle to request database version change

<script> function openDB(name){var request= window.indexeddb.open (name)// create indexedDB request.onerror=function (e){ Console. log('open indexDB error')} request.onsuccess=function (e){mydb.db =e.target.result }} var myDB={name:'testDB', version:'1', db:null } openDB(myDB.name) </script>Copy the code

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

  • Closed with IndexedDB –indexdb.close()
function closeDB(db){
    db.close();
}
Copy the code
  • Remove with IndexedDB –window.indexedDB.deleteDatabase(indexdb)
function deleteDB(name) {
  indexedDB.deleteDatabase(name)
}
Copy the code

3. Differences between WebStorage, Cookie, and IndexedDB

As you can see from the table above, cookies are no longer recommended for storage. LocalStorage and sessionStorage can be used if you don’t have extensive data storage requirements. For data that does not change much, try to use localStorage, otherwise use sessionStorage.

conclusion

It is the emergence and development of browser storage and cache technology that brings infinite opportunities for our front-end applications. In recent years, third-party libraries based on storage and caching technology emerge in an endless stream. Besides, excellent Web application models such as PWA have been derived. Summarize the core points of this paper:

  • The job of a Cookie is not to store it locally, but to “maintain state.”
  • Web Storage is a data Storage mechanism provided by HTML5 specifically for browser Storage, which does not communicate with the server
  • IndexedDB is used by clients to store large amounts of structured data

To recommend a good BUG monitoring toolFundebug, welcome free trial!

Refer to the article

  • Let’s get cookie straight
  • HTML5 Local Storage — IndexedDB (1: Basic Use)
  • Cookie, LocalStorage and SessionStorage
  • Front-end performance optimization principles and practices
  • Localstorage will know will know
  • IndexedDB for Browsers