Very comprehensive front-end local storage explanation, storage explanation

Source: Internet
Author: User
Tags createindex setcookie sessionstorage

Very comprehensive front-end local storage explanation, storage explanation
Three Local Storage Methods: cookiePreface

One of the biggest problems in the early days of the network was how to manage the status. In short, the server cannot know whether two requests come from the same browser. At that time, the simplest way was to insert some parameters in the page during the request and send back parameters in the next request. This requires using a hidden form containing parameters or passing it as part of a URL parameter. Both solutions are manual and error-prone. Cookie appears to solve this problem.

Function

Cookie is plain text and there is no executable code. Store Data. When a user accesses a website (webpage), we can store data to the visitor's computer through cookies, or some websites store data (usually encrypted) on the user's local terminal to identify users and track sessions)

How to work

When an http request is sent to a webpage, the browser first checks whether the corresponding cookie exists. If yes, it is automatically added to the cookie field in the request header. These are what browsers automatically help us, and each http request will automatically help us. This feature is important because it relates to "What kind of data is suitable to be stored in cookies ".

The data stored in the cookie is automatically stored in the http request by the browser each time. If not all the data needs to be sent to the server, the automatic processing of browser settings undoubtedly increases network overhead. However, if the data is the data that each request needs to send to the server (such as identity authentication information ), the browser automatically removes the need for repeated adding operations. Therefore, the setting of "the information to be carried in each request (the most typical is the identity authentication information)" is particularly suitable for storing in cookies, and other types of data are not suitable.

Features The cookie value can be set or read.Set

Client settings

Document. cookie = 'name = value'; document. cookie = 'username = cfangxu; domain = baike.baidu.com 'and set the effective domain

Note:The client can set the following cookie options: expires, domain, path, and secure (conditional: the client can successfully set the secure type cookie only on the https webpage ), however, the HttpOnly option cannot be set.

Server Settings 
Whether you are requesting a resource file (such as html/js/css/image) or sending an ajax request, the server will return response. One of the response Headers is set-cookie, which is used by the server to set cookies.

The Set-Cookie message header is a string in the following format (optional in the brackets): Set-Cookie: value [; expires = date] [; domain = domain] [; path = path] [; secure]

Note:Only one Cookie can be set for one set-cookie field. To set multiple cookies, you must add the same number of set-cookie fields.
The server can set all cookie options: expires, domain, path, secure, HttpOnly
The options specified through Set-Cookie are only used on the browser side, and are not sent to the server side.

Read

We use document. cookie to obtain the cookie of the current website. It contains all the cookies of the current website (to prevent cross-origin scripting (xss) attacks, this method can only obtain non-HttpOnly cookies ). It concatenates all cookies by a semicolon + space, for exampleusername=chenfangxu; job=coding

Modify cookie

To modify a cookie, you only need to assign a value again. The old value will be overwritten by the new value. Note that when setting a new cookie, the path/domain options must be the same for the old cookie. Otherwise, a new cookie is added instead of modifying the old value.

Delete

Set the expiration time of the cookie to be deleted to the past time. The path/domain/options must be the same for the old cookie.

Note:

If only one value is set, the value in the cookie is counted. If the two cookies are set with the same key value, the preceding values will be overwritten.

Cookie attributes (optional)Expiration time

If you want to store a cookie for a long time. You need to set an expiration time for this cookie at the same time. If this parameter is not set, the cookie is stored on a temporary basis by default. The cookie is automatically destroyed when the browser closes the process.

Note: document. cookie = 'name = value; expires = '+ GMT (Greenwich Mean Time) format date string;

General days: new Date (). setDate (oDate. getDate () + 5); 5 days more than the current time

An example of setting cookie Timeliness

Function setCookie (c_name, value, expiredays) {var exdate = new Date (); exdate. setDate (exdate. getDate () + expiredays); document. cookie = c_name + "=" + escape (value) + (expiredays = null )? "": "; Expires =" + exdate. toGMTString ()} usage: setCookie ('username', 'cfangxu ', 30)
Expires is an option in http/1.0. In the new http/1.1 protocol, expires has been replaced by the max-age option. Both of them are used to limit the cookie validity period. The expires value is a time point (cookie expiration time = expires ), the value of max-age is a time period in seconds (cookie failure time = creation time + max-age ).
In addition, the default value of max-age is-1 (that is, the validity period is session). max-age has three possible values: Negative, 0, and positive.
Negative number: Valid session;
0: Delete the cookie;
Positive: Validity Period: Creation Time + max-age
Cookie domain concept (domain option)

Domain specifies the domain in which the cookie will be sent. By default, domain is set to the domain name of the page on which the cookie is created. Therefore, when a request is sent to the same domain name, the cookie is sent to the server.

The browser compares the domain value with the requested domain name at the end (that is, starting from the end of the string) and sends the matching cookie to the server.

Client settings

document.cookie = "username=cfangxu;path=/;domain=qq.com" 
As shown above: "www.qq.com" and "sports.qq.com" share an associated domain name "qq.com". If we want the cookie under "sports.qq.com" to be accessed by "www.qq.com, we need to use the domain attribute of the cookie and set the path attribute "/".

Server Settings

Set-Cookie: username=cfangxu;path=/;domain=qq.com 
Note: It must be the access between the same domain. The domain value cannot be set as a domain name of a non-primary domain.

Cookie path concept (path option)

Generally, a cookie is created because the user accesses the page. However, the cookie is not accessible only on the page where the cookie is created.
Due to security considerations, by default, only webpages in the same directory or subdirectory as the page for cookie creation can be accessed.
That is, the path attribute can specify a cookie for a specific document on the server. The url path with the prefix set for this attribute is valid.

Client settings

The most common example is to make the cookie under the root directory so that no matter which sub-page is created, all the pages can be accessed.

document.cookie = "username=cfangxu; path=/"

Server Settings

Set-Cookie:name=cfangxu; path=/blog

The preceding settings: the path option value matches/blog,/blogrool, and so on. Any options starting with/blog are valid. Note that the path attribute is compared only after the domain option is verified. The default value of the path attribute is the path part of the URL corresponding to the Set-Cookie message header.

Summary of domain and path:

Domain is a domain name and path is a path. The two constitute a URL. domain and path are used together to restrict which URLs can be accessed by cookies.
Therefore, the domain and path2 options jointly determine when the cookie will be automatically added to the Request Header by the browser and sent out. If these two options are not set, the default value is used. The default value of domain is the domain name of the webpage that sets the cookie, and the default value of path is the directory of the webpage that sets the cookie.

Cookie Security (secure option)

Generally, cookie information is transmitted through an HTTP connection. This transmission method is easy to view, so the information stored in cookies is easily stolen. If the content transmitted in cookies is important, encrypted data transmission is required.

The secure option is used to set the cookie to be sent only for secure requests. When the request is HTTPS or other security protocols, the cookie containing the secure option can be sent to the server.

document.cookie = "username=cfangxu; secure"

Setting the cookie as secure only ensures that the data transmission process between the cookie and the server is encrypted, while the cookie files stored locally are not encrypted. Even if the secure attribute is set, it does not mean that others cannot see the cookie information stored locally on your machine. Confidential and sensitive information should never be stored or transmitted in cookies, because the entire mechanism of cookies is inherently insecure.

Note: If you want to set a secure-type cookie through js on the client or webpage, you must ensure that the webpage is https. The secure type cookie cannot be set on the http webpage.

HttpOnly

This option is used to set whether the cookie can be accessed through js. By default, the cookie does not contain the httpOnly option (that is, it is null). By default, the client can access the cookie through js Code (including reading, modifying, and deleting the cookie) this cookie. When the cookie contains the httpOnly option, the client cannot access (including reading, modifying, and deleting) the cookie through js Code.

In the client, you cannot set an httpOnly type cookie through js Code. This type of cookie can only be set through the server.

Cookie Encoding

Cookie is actually a string, but this string contains medium numbers, semicolons, and spaces as special characters. Therefore, when the key and value of a cookie contain these three special characters, extra encoding is required. Generally, escape is used for encoding and unescape is used for decoding; you can also use encodeURIComponent/decodeURIComponent or encodeURI/decodeURI.

Third-party cookies

Generally, the cookie domain matches the domain of the browser address, which is called the first-party cookie. Third-party cookies are the domain of cookies that do not match the domain in the address bar. Such cookies are usually used on third-party advertising websites. To track users' browsing records and push ads to users based on their browsing habits.

  • Cookie recommendation Resources

    • Chat cookie
    • HTTP cookies
LocalStorage (Local Storage)

New HTML5 method,IE8 and aboveAll browsers are compatible.

Features
  • Life cycle: persistent local storage. Data will never expire unless data is actively deleted.
  • The stored information is shared in the same domain.
  • When localStorage is added (added, modified, or deleted) on this page, this page does not trigger the storage event, but other pages will trigger the storage event.
  • Size: 5 MB (related to browser vendors)
  • You can open it locally in a non-IE browser. The IE browser must be opened on the server.
  • LocalStorage is essentially a string reading function. If the storage content is large, memory space is consumed, leading to page card change.
  • LocalStorage is restricted by the same-source policy.
Set

localStorage.setItem('username','cfangxu');

Obtain

localStorage.getItem('username') 
You can also obtain the key name.
LocalStorage. key (0) # obtain the first key name

Delete

localStorage.removeItem('username') 
You can also clear all buckets at a time.
localStorage.clear()

Storage event

Triggered when storage changes.
Note:Storage operations on the current page will trigger storage events on other pages
The event Callback Function has a parameter event, which is a StorageEvent object and provides some practical attributes, as shown in the following table:

Property Type Description
Key String The named key that was added, removed, or moddified
OldValue Any The previous value (now overwritten), or null if a new item was added
NewValue Any The new value, or null if an item was added
Url/uri String The page that called the method that triggered this change
SessionStorage

In fact, it is similar to localStorage. It is also local storage and session local storage.

Features:
  • It is used to locally store data in a session. The data can be accessed only on pages in the same session, and the data will be destroyed after the session ends. SessionStorage is not a persistent local storage, but a session-level storage. That is to say, as long as the browser window is not closed, even if the page is refreshed or another page is accessed from the same source, the data still exists. When the window is closed, sessionStorage is destroyed, or another page with the same source is opened in the new window. sessionStorage does not exist.
Differences between cookie, localStorage, and sessionStorage
  • Same: Local (Browser Side) Data Storage
  • Different:

    LocalStorage and sessionStorage

    LocalStorage can read/modify the same localStorage data under the same protocol, the same host name, and the same port.

    SessionStorage is more rigorous than localStorage. In addition to protocols, host names, and ports, sessionStorage must be in the same window (that is, the tab of the browser.

    LocalStorage is a permanent storage unless it is manually deleted.

    SessionStorage is automatically destroyed when the session ends (when the current page is closed)

    Cookie data will be sent to the server at the same time each time an http request is sent, while localStorage and sessionStorage will not.

 

Extends other front-end storage methods (not commonly used) for web SQL databases

There are several reasons for the replacement:

IndexedDB
Explanation from MDN: indexedDB is a low-level API used by clients to store a large amount of structured data (including file/blobs ). This API uses indexes to achieve high-performance search for the data. Although Web Storage is useful for storing a small amount of data, this method is not very useful for storing more structured data. IndexedDB provides a solution.

So,IndexedDBThe API is powerful, but it may seem too complicated for simple situations. It depends on whether your business scenario is used or not.

indexedDBIs a JavaScript-based object-oriented database.IndexedDBAllows you to store and retrieve key-indexed objects;

IndexedDB encourages the following basic modes:

  • Open the database and start a transaction.
  • Create an object store.
  • Construct a request to perform some database operations, such as adding or extracting data.
  • Listen to DOM events of the correct type to wait for the Operation to complete.
  • Perform some operations on the operation result (which can be found in the request object)
1. First open the indexedDB Database

Syntax:
window.indexedDB.open(dbName, version)

Var db; // open the database, and open has the second parameter version number var request = window. indexedDB. open ('mytestdatabase'); // request after the database is opened successfully. onsuccess = function (event) {// store data results. All subsequent database operations cannot be separated from it. Db = request. result;} request. onerror = function (event) {alert ("Why didn't you allow my web app to use IndexedDB ?! ");} // The first database version created, or the new version passed by window. indexedDB. open (the version value is higher than the current one) request. onupgradeneeded = function (event ){}

Onupgradeneeded event:Update the schema of the database, that is, create or delete an object bucket. This event will be used asversionchangeA part of the transaction is called. When the database is opened for the first time or when the specified version number is higher than the version number of the currently Persistent DatabaseversionchangeThe transaction is created.onupgradeneededIt is the only place where we can modify the database structure. Here, we can create and delete object buckets and create and delete indexes.

2. Build a database

IndexedDB uses Object Storage space instead of tables, and a single database can contain any number of object storage space. Each time a value is stored in an object bucket, it is associated with a key.

// Create a version for the database for the first time, or window. indexedDB. the new version passed by open (the version value is higher than the current one) request. onupgradeneeded = function (event) {// didn't we get db in success before? Why do we need to get it here, // The success event var db = event.tar get will be executed only after the current event function is executed. result; // create an object bucket. The keyPath is id, and the keyGenerator is an auto-incrementing var objectStore = db. createObjectStore ('testitem', {keyPath: 'id', autoIncrement: true}); // create an index to search by id. IDs are auto-incrementing and will not be duplicated, so you can use the unique index objectStore. createIndex ('id', 'id', {unique: true}) objectStore. createIndex ('name', 'name'); objectStore. createIndex ('age', 'age'); // Add an information path to the objectStore in the database. add ({name: 'cfangxu ', age: '27 '});}

Note:After execution, you cannot see the indexedDB In the debugging toolbar Application. You must right-click and refresh it.

Syntax for creating an index:

ObjectStore. createIndex (indexName, keyPath, objectParameters) indexName: name of the created index. An empty name can be used as the index. KeyPath: the Key Path used by the index. You can use an empty keyPath or use keyPath as the array keyPath. ObjectParameters: Optional. One of the common parameters is unique, which indicates whether the field value is unique and cannot be repeated. For example, the IDs in this demo cannot be repeated, so there are settings:
3. Add data

The above code has created a field and added a piece of data, but if we want to operate outside the onupgradeneeded event, the next step will be done.
Because database operations are performed based on transactions, we must first create a transaction, whether it is to add, edit, or delete a database ), then you can continue the following operations.
Syntax:var transaction = db.transaction(dbName, "readwrite"); 
The first parameter is the list of object buckets to be crossed by a transaction, which can be an array or a string. If you want transactions to span all object storage spaces, You can input an empty array. If you do not specify anything for the second parameter, you get a read-only transaction. Because we want to write data here, we need to pass in the "readwrite" identifier.

Var timer = setInterval (function () {if (db) {clearInterval (timer); // create a transaction var transaction = db. transaction (['testitem'], 'readwrite'); // open a storage object var objectStore = transaction. objectStore ('testitem'); // Add data to the objectStore. add ({name: 'xiaoming', age: '12'}); objectStore. add ({name: 'xiaolong', age: '20'}) ;}, 100)

Why should I use an interval timer?Because this is a demo, it is normal that you have to perform operations to write data to the database. In our demo, JavaScript Execution to transaction is faster than the onsuccess Event Callback of indexedDB, as a result, the db is undefined, so I wrote an interval timer and waited for it for a while.

4. Get Data
Var transaction = db. transaction (['testitem'], 'readwrite'); var objectStore = transaction. objectStore ('testitem'); var getRquest = objectStore. get (1); getRquest. onsuccess = function (event) {console. log (getRquest. result);} // output: {name: "cfangxu", age: "27", id: 1}
5. modify data
Var transaction = db. transaction (['testitem'], 'readwrite'); var objectStore = transaction. objectStore ('testitem'); var getRquest = objectStore. put ({name: 'chenfangxu ', age: '27', id: 1}); // modify the data with id 1.
6. delete data
Var transaction = db. transaction (['testitem'], 'readwrite'); var objectStore = transaction. objectStore ('testitem'); var getRquest = objectStore. delete (1); // delete the data with id 1
After the above example is executed, you must right-click to refresh indexedDB, which will not change.
I have a front-end learning exchange QQ group: 328058344 if you encounter any problems during the process of learning the front-end, please come to my QQ Group to ask questions. The group will update some learning resources every day. Chat is prohibited.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.