client data store

client data store

introduction

With the advent of web applications came the need to be able to store user information directly on the client side. The idea is logical that information belonging to a particular user should exist on that user's machine. Whether login information, preferences or other data, web application providers are finding ways to store data on the client.
Let's use a table to summarize the advantages and disadvantages of various ways of storing data on the client

Way advantage shortcoming
cookie (1) It can be used to communicate with the server; (2) When the cookie is about to expire, the expires in the cookie can be reset instead of deleted. (1) same-origin restriction, (2) it will be sent along with http header information, increasing network traffic (load of document transmission); (3) it can only store a small amount of data; (4) it can only store characters string; (5) There are potential security issues.
sessionStorage (1) Storage of small pieces of data for the session, that is, the data is only kept until the browser is closed. (2) Data stored in it can exist across page refreshes. Same-origin policy restriction: If you want to operate the same sessionStorage between different pages, these pages must be under the same protocol, the same host name and the same port
localStorage If you do not use removeItem() or delete to delete, or the user does not clear the browser cache, the data will always be saved on disk, so it is very suitable for storing documents on the client side or saving user preferences for a long time (1) Same-origin restriction, (2) localStorage is essentially a read of strings, which is a synchronous operation, and if there is a lot of storage content, it will consume memory space and cause the page to become stuck
userDate ------ (1) Same-origin restriction: The access restriction of userData is the same as that of cookies, it must come from the same domain name, under the same path, and use the same protocol as the storage script to access (2) userData is only for ie Data storage (3) userData has potential security issues.
indexedDB IndexedDB will not lock the browser during operation, it is an asynchronous operation, and users can still perform other operations. Asynchronous design prevents reading and writing of large amounts of data, slowing down the performance of web pages Same-origin restriction: IndexedDB is subject to the same-origin restriction. Each database corresponds to the domain name where it was created. Web pages can only access databases under their own domain name, but not cross-domain databases.
One. cookie
  • The first solution to this problem exists in the form of cookies.

  • HTTP Cookie, usually directly called cookie, was originally used to store session information on the client side.

  • The purpose of the cookie is to facilitate us to distinguish the situation of the client that http requests it.

    Because for the http request, it is stateless. The so-called stateless is: when my http request ends, the connection is closed. Then the next time I want to initiate the same request and reach the server, the server will not know that this request is from the same client as a previous request. It cannot track the session of the http request, what happened. That is to say, after this http request is closed, no matter which http request arrives in the future, it does not know its association with any previous http. This is a feature brought by the http protocol --- the http protocol itself is stateless.
    Because http requests are stateless, cookies are needed to maintain client state.
    In other words, cookies can be used as an identifier to maintain a state between the client and the browser. It can let the server know which client http comes from through cookie.

  • The two main functions of cookies, the first function is to solve the shortcomings of http statelessness, and the second function is to use cookies to store some other data on the client

1. Take a look at the definition of cookies:

Cookie refers to the data stored on the user's local terminal. The cookie data will be automatically transmitted between the web browser and the web server, that is to say, when an HTTP request is sent, all cookie values ​​stored under the requested domain name will be sent to the web server, so server-side scripts can read and write storage Operation of cookies on the client side.

2. Limits on the number and size of cookies:

The number of cookies saved by each web server (domain name) is limited, but it varies from browser to browser.

browser IE6.0 IE7.0 and later Firefox stopped Safari Chrom
number of cookies 20 50 50 30 unlimited unlimited
cookie size 4095B 4095B 4096B 4097B 4097B 4097B
3. Composition of cookies:

Generally speaking, a cookie is composed of the following pieces of information saved by the browser  
(1) name (name): a name that uniquely determines the cookie  
(2) value (value): a string value stored in the cookie, the value must Encoded by URL  
(3) domain (domain): for which domain the cookie is valid, all requests sent to this domain will contain this cookie information (4) path (  
path): for the path in the specified domain, it should be sent to the server cookie  
(5) expiration time (expires): the time stamp indicating when the cookie should be deleted  
(6) security flag (secure): After specifying, the cookie is only sent to the server when using an SSL connection.
Note in particular that the domain, path, expiration time, and secure flag are all hints from the server to the browser to specify when the cookie should be sent. These parameters are not sent as part of the cookie information sent to the server, only name-value pairs are sent.

4. JavaScript and cookies
  • In JavaScript, you can use the document.cookie property to get cookies. When used to obtain attribute values, document.cookie returns the string of all cookies available on the current page (according to the domain, path, expiration time and security settings of the cookie), a series of name-value pairs separated by semicolons, as follows As shown in the example:
    insert image description here
    For example: the format of name1=value1;name2=value2;name3=value3.
    All names and values ​​are URL-encoded, so must be decoded using decodeURIComponent().
    When used to set a value, the document.cookie property can set a new cookie string. This cookie string is interpreted and added to the existing cookie collection.

  • Since reading and writing cookies in JavaScript is not very intuitive, it is often necessary to write some functions to simplify the functions of cookies. There are three basic cookie operations: read, write, and delete. They are represented in the CookieUtil object as follows.

    var CookieUtil = {
    
      get: function(name) {
            var cookieName = encodeURIComponent(name) + "=",
            cookieStart = document.cookie.indexOf(cookieName),
            cookieValue = null;
       
            if(cookieStart > -1) {
                var cookieEnd = document.cookie.indexOf(";", cookieStart);
                 if (cookieEnd == -1) {
                           cookieEnd = document.cookie.length;
                 }
           cookieValue = decodeURIComponent(document.cookie.substring      (cookieStart + cookieName.length, cookieEnd));
             }
       return cookieValue;
       },
       set: function(name, value, expires, path, domain, secure) {
                var cookieText = encodeURIComponent(name) + "=" +            encodeURIComponent(value);
                if(expires instanceof Data) {
                         cookieText += ";expires=" + expires.toGMTString();
                  }
              if(path) {
                       cookieText += ";path=" + path;
               }
              if(domain) {
                    cookieText += ";domain=" + domain;
               }
              if(secure) {
                    cookieText += ";secure";
               }
              document.cookie = cookieText;
      },
      unset: function(name, path, domain, secure) {
              this.set(name, "", new Date(0), path, domain, secure);
      }
    }
    

    There are three methods in the function: get, set, unset.

    CookieUtil.set(name, value, expires, path, domain, secure) first uses a variable to receive the encoded string "name=value", and the four if judgments respectively judge the values ​​of the input parameters expires, path, domain, secure, These values, if present, are appended to the string.

    CookieUtil.get(name) first defines a cookieName variable to receive the encoded string "name=", and then uses a cookieStart variable to receive the indexOf() method of the document.cookie attribute, which returns the initial subscript of cookieName , if the string cookieName is not found, return -1. If judges that if cookieName is not -1, further calculate the last subscript of cookName. The substring() method rebuilds a string from the last subscript of "name=" to the ; position. That is the value value.

    The unset() method is to use the same path, domain and security options to delete the cookie by setting the expiration time to the past time.

  • Child cookie
    To get around the browser's single-domain cookie data restrictions, some developers use a concept called subcookies. Subcookies are smaller pieces of data stored within a single cookie. That is to use the value of the cookie to store multiple name-value pairs. The common format of sub-cookies is as follows:
    name=name1=value1&name2=value2&name3=value3
    Sub-cookies are generally formatted in the format of query strings. These values ​​can then be stored and accessed using a single cookie, rather than using a different cookie store for each name-value pair. Finally, websites or web applications can store more structured data without reaching the upper limit of single-domain cookies.

2. IE user data

Although H5 can store data through localstorage and sessionstorage, but the lower version of ie does not support it, what should I do?
In order to store data in ie, Microsoft introduced the concept of persistent user data through a custom behavior

1. What is userData?

userData is a data storage method of ie. userData storage saves data by writing data into a UserData storage area. userData saves data on the client in XML format. UserData storage method is only applicable to IE browser. The data will always exist, unless you manually delete it or use a script to set the expiration date of the data.
Generally speaking, userData allows each document to store up to 128KB of data, and each domain name has a maximum of 1MB of data, which is larger than the data stored in cookies.

2. How to use userData to store data

If we want to use userData to store data, first we must specify userData behavior on some element using css

  <div style="behavior:url(#default#userData)" id="dataStore"></div>  

Once the element uses the userData behavior, you can use the setAttribute() method to save data on it. In order to submit the data to the browser cache, you must also call the save() method and tell it the name of the data space to save to , the name of the data space can be completely arbitrary and is only used to distinguish different data sets.

 var dataStore = document.getElementById("dataStore");
 dataStore.setAttribute("ifClick", "true");
 dataStore.save("ClickInfo");  

In the above code, after using setAttribute to store data, the save method is called, and the name of the data space ClickInfo is specified. After the next page load, you can use the load method to specify the same data space to obtain data

  dataStore.load("ClickInfo");
  dataStore.getAttribute("ifClick");  

If getAttribute() calls a name that does not exist or has not been loaded, it returns null, and we can also use the removeAttribute() method to delete a certain data

   dataStore.removeAttribute("ifClick");
3. Web storage mechanism

HTML5 provides two new ways to store data on the client side: localStorage and sessionStorage.

1. What is Web Storage

Web Storage is also a mechanism for storing data on the client side. The main purpose is to overcome the limitations that cookies are not suitable for storing large amounts of data and other limitations. They can store a large amount of cross-session data. 
The original Web Storage contains the definition of two objects: sessionStorage and globalStorage. Both are only saved in the client (ie browser) and do not participate in communication with the server. This means that the data will not be stored on the server. Both objects exist as properties of the window object in supported browsers. Now localStorage replaces globalStorage in the revised HTML5 specification as a solution for persistent storage of client data.

2.Storage type
  • clear(): delete all values//Firefox is not implemented
  • getItem(name): Get the corresponding value according to the specified name name
  • key(index): Get the name of the value at the index position
  • removeItem(name): delete the name-value pair specified by name
  • setItem(name,value): Set a corresponding value for the specified name
3.sessionStorage

(1) What is sessionStorage  
The sessionStorage object is to store data specific to a certain session, that is, the data is only saved until the browser is closed. This object is like a session cookie, and it will disappear after the browser is closed. The data stored in sessionStorage Can exist across page refreshes
(2) How to use sessionStorage to store data  
The sessionStorage object is an instance of Storage.
When storing data, you can use setItem() or directly set new properties to store data. Recommended method of use.

  //  使用方法存储数据
  sessionStorage.setItem("ifClick", "true");
  //  使用属性存储数据
   sessionStorage.ifClick = "true";  

(3). When we want to get some data, we can use getItem to get the data

 sessionStorage.getItem("ifClick");  
4.globalStorage

(1) What is globalStorage  
As part of the original Web Storage, the purpose of this object is to store data across sessions, but with specific access restrictions.
Note here that globalStorage is not an instance of Storage, but globalStorage[name] is an instance of Storage.
(2) How to use globalStorage to store data  
To use globalStorage, you must first specify which domains can access the data, which can be achieved by using attributes marked with square brackets

globalStorage["aaa.com"].ifClick = "true";  

In the above code, the storage space for the domain name aaa.com is accessed. This storage space is accessible to aaa.com and all its subdomains. We can get the data as follows

 globalStorage[aaa.com].getItem("ifClick");  

Because globalStorage is less used now, if you want to use it, use localStorage

5.localStorage

(1) What is localStorage?  
The localStorage object replaces globalStorage in the revised html5 specification as a solution for persistent storage of client data. Unlike globalStorage, no access rules can be specified for localStorage, because the rules have been set in advance. To access the same A localStorage object, the page must come from the same domain name, use the same protocol, and use the same port
(2) How to use localStorage to store data  
Since localStorage is an instance of Storage, it can be used like sessionStorage

 localStorage.setItem("ifClick","true");  

When we want to get data, we can get it like this

  localStorage.getItem("ifClick");  

The data stored in localStorage follows the same rules as the data stored in globalStorage, and the data is kept until it is deleted through js or the user clears the browser cache

Summary: Both sessionStorage and localStorage overcome some limitations of cookies. They all have many common features. The only difference between localStorage and sessionStorage is that localStorage belongs to permanent storage, while sessionStorage belongs to key-value pairs in sessionStorage when the session ends. will be cleared

5. IndexedDB
1. Why there is IndexedDB

Existing browser data storage solutions are not suitable for storing large amounts of data: the size of the cookie does not exceed 4KB
, and each request will be sent back to the server;
Provides a search function and cannot create a custom index, so a new solution is needed, which is the background of the birth of IndexedDB

2. What is IndexedDB

In layman's terms, IndexedDB is a local database provided by the browser, which can be created and operated by web scripts. IndexedDB allows storing large amounts of data, provides a search interface, and can also create indexes, which are not available in LocalStorage.

Guess you like

Origin blog.csdn.net/qq_44875145/article/details/100826968