From any Chrome TAB, press F12 and click the “Application” TAB to see all the ways the browser can store local Storage in the “Storage” bar on the left side of the console:

  • Local Storage
  • Session Storage
  • Cookies
  • Web SQL
  • IndexedDB
  • Trust Tokens

Local Storage

HTML5 new approach, but compatible with IE8 and above.

Window.localstorage (or directly localStorage) refers to a localStorage object that can be used to access the localStorage space of the current origin.

Features:

  1. Life cycle: Persistent local storage that never expires unless it is actively deleted;
  2. Local of the same originStorageObjects are shared and cannot access local from different sourcesStorageObject (same origin policy);
  3. Store objects are simple key-value stores, similar to objects, but they remain intact when the page loads. Keys and values are always strings;
  4. The Storage size varies with browsers. Generally, the Storage size is about 5M.
  5. When adding, modifying, or deleting localStorage on this page, this page will not trigger the storage event, but all other pages in the same domain name will trigger the storage event.
  6. LocalStorage is essentially a string read, if the storage content is too much, it will consume memory space, will cause pages to become jammed;

Usage:

You can access a Storage as if it were an object or use its built-in methods.

  • Settings:
localStorage.colorSetting = '#a4509b';
localStorage['colorSetting'] = '#a4509b';
localStorage.setItem('colorSetting'.'#a4509b');
Copy the code
  • Read:
let cat1 = localStorage.myCat;
let cat2 = localStorage['myCat'];
let cat3 = localStorage.getItem('myCat');
Copy the code
  • Delete:
// Delete an item
localStorage.removeItem('uselessItem');
// Delete all items
localStorage.clear();
Copy the code

Object properties:

There is only one read-only property: length, which returns an integer representing the number of data items stored in the Storage object.

Storage:

When a Storage object changes, the Storage event is triggered. However, the page that causes the localStorage object to change does not trigger this event, but all other pages under the same domain name. Except Internet Explorer, it will trigger the storage event on all pages.

Add event listener on test.cn/a (a page) :

window.addEventListener('storage', callback);
Copy the code

Add, delete, or modify a Storage object on test.cn/b:

localStorage.setItem('test'.'xxx');
Copy the code

If the Storage object is changed on page A, the callback function will not be executed.

The event argument in the callback function, which is a StorageEvent object, has the following utility properties:

attribute type describe
key String The key of the property of the Storage object to be changed (added, deleted, modified)
oldValue Any The value that was changed previously, or oldValue=null if it was added
newValue Any NewValue =null if the value is deleted
url String Changes the PAGE URL of a Storage object

Note: If localstorage.clear () is called, key, oldValue, and newValue are all null.

Session Storage

SessionStorage allows you to access a sessionStorage object corresponding to the current source. It is similar to localStorage, with the following differences:

localStorage sessionStorage
Storage time Permanent storage unless manually deleted Is cleared at the end of the page session
Objects share Pages with the same protocol, domain name, and port number share the same localStorage object In addition to the same protocol, domain name, and port number, a sessionStorage object can be shared only in the same window
Storage events Other pages that share localStorage will trigger the storage event The sessionStorages for each tag are isolated, so they cannot communicate. Storage events for sessionStorage are only fired in other IFrame frames on the same TAB.
  • The page session remains as long as the browser is open, and the original page session remains when the page is reloaded or restored.
  • The top-level browsing session context is copied as the context for the new session when a new TAB or window opens a page, unlike session cookies.
  • Opening multiple Tabs pages with the same URL creates their ownsessionStorage.
  • Close the corresponding browser Window (Window/TAB) to clear the correspondingsessionStorage.

The usage method and properties are the same as localStorage.

Cookies

An HTTP Cookie (also known as a Web Cookie or browser Cookie) is a small piece of data that a server sends to a user’s browser and keeps locally. It is carried and sent to the server the next time the browser makes a request to the same server. Typically, it is used to tell the server whether two requests are from the same browser, such as to keep the user logged in. Cookies make it possible to record stable state information over stateless HTTP protocols.

A Cookie is essentially a key-value pair.

Cookie’s purpose:

Cookies are mainly used in the following three aspects:

  1. Session state management (such as user login status, shopping cart, game score, or other information that needs to be recorded);
  2. Personalized Settings (such as user – defined Settings, themes, etc.);
  3. Browser behavior tracking (e.g. tracking and analyzing user behavior, etc.);

HTTP create Cookie:

Server: When receiving an HTTP request, the server can add several set-cookie options in the response header, each representing a Cookie and its corresponding configuration; Client: After receiving the response, the browser usually saves the Cookie and sends the Cookie information to the server through the Cookie request header in each request to the server.

For example, the response of the server:

HTTP / 1.0 200 OK
Content-type: text/html
Set-Cookie: yummy_cookie=choco
Set-Cookie: tasty_cookie=strawberry
Copy the code

After the client request content:

GET /sample_page.html HTTP / 1.1
Host: www.example.org
Cookie: yummy_cookie=choco; tasty_cookie=strawberry
Copy the code

Cookie-related attributes:

The server adds optional attributes to the Cookie in each set-cookie header of the response to specify its expiration time, domain, path, expiration date, applicable site, and so on.

  • Expires=

    : Indicates the maximum validity period of a cookie in the form of a timestamp that complies with the HTTP-date specification. If this property is not set, then this is a session cookie. A session ends when the client is shut down, which means that session cookies are removed at that time. However, many Web browsers support session recovery, which allows the browser to keep all TAB tabs and then restore them when the browser reopens. At the same time, the cookie is restored as if the browser had not been closed;

  • Max-age =

    : indicates the number of seconds that must pass before the cookie expires. A number of seconds of 0 or -1 will expire the cookie directly. Some older browsers (IE6, IE7, and IE8) do not support this property. For other browsers, if both Expires and max-age are present, max-age takes precedence.

  • Domain=

    : specifies the host name to which the cookie can be delivered. If not specified, the default is the host part of the current document access address (but not the subdomain). Unlike the previous specification, the dot before the domain name is ignored. If a domain name is specified, then each subdomain name is also included;

  • Path= : specifies a URL Path that must appear in the Path of the requested resource before the Cookie header can be sent. The character %x2F (“/”) can be interpreted as a file directory separator, and the subdirectories of this directory also match (for example, if path=/docs, then “/docs”, “/docs/Web/”, or “/docs/Web/HTTP” all match);

  • Secure: A cookie with a Secure attribute is sent to the server only when the request uses SSL and HTTPS protocols. However, confidential or sensitive information should never be stored or transmitted in HTTP cookies, because the entire mechanism is inherently insecure, such as the foregoing protocol does not mean that all information is encrypted. Note: Insecure sites (HTTP:) can no longer set the secure directive in cookies (a new restriction introduced in Chrome 52+ and Firefox 52+);

  • HttpOnly: Cookies with the HttpOnly attribute cannot be accessed using JavaScript via the Document.cookie attribute, XMLHttpRequest, and RequestAPIs, and can be used to defend against cross-site scripting attacks (XSS);

  • SameSite=Strict/Lax: When Strict is set to Strict, the Cookie cannot be sent across domains. When “Lax” is used, cookies cannot be sent across domains except in the following three cases:

    • Links:<a href="..." ></a>
    • Preload request:<link rel="prerender" href="..." />
    • GET the form:<form method="GET" action="..." >

Cookie prefix:

  • __Secure- prefix: Cookies prefixed with __Secure- (where the hyphen is part of the prefix) must be set along with the secure property and must be applied to secure pages (pages accessed using HTTPS).
  • __Host – prefix: Cookies prefixed with __Host- must be set with the secure property, must be applied to secure pages (pages accessed using HTTPS), must not be able to set the domain property (thus not sent to subdomains), and the path property must have a value of “/”.
// When the response comes from a secure domain (HTTPS), both can be accepted by the clientSet-Cookie: __Secure-ID=123; Secure; Domain=example.com
Set-Cookie: __Host-ID=123; Secure; Path=/ // The Secure directive is missing and will be rejectedSet-Cookie: __secure-id =1 // Will be rejected if Path=/ is missingSet-Cookie: __Host-id=1; Secure // Will be rejected because the domain property is setSet-Cookie: __Host-id=1; Secure; Path=/; domain=example.com
Copy the code

Cookie type:

  1. Session cookies: Session cookies will be removed when the client shuts down. Session cookie does not set Expires or max-age directives. Note that browsers usually support session recovery.

    Set-Cookie: sessionid=38afes7a8; HttpOnly; Path=/
    Copy the code
  2. Persistent cookies: Persistent cookies do not expire when the client closes, but expire after a specified date (Expires) or a specified period of time (max-age).

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

Js operation Cookie:

Js can only operate on cookies that are not httpOnly set.

  • Check whether the Cookie function is enabled in the browser:

    // true Indicates that the Cookie function is enabled
    window.navigator.cookieEnabled;
    Copy the code
  • See the cookies:

    cosnt cookie = document.cookie;
    Copy the code

    The read Cookie is a string containing all cookies, each Cookie preceded by a semicolon and a space (;). Delimited (that is, key=value key-value pairs).

  • Increase the cookies:

    document.cookie = newCookie;
    Copy the code

    NewCookie is a key-value pair string. Note that only one cookie can be set or updated at a time using this method.

    • The following optional Cookie attribute values can be followed by key-value pairs to specify the setting/update of the Cookie, separated by a semicolon:

      • ; Path =path (e.g. ‘/’, ‘/mydir’) if not defined, defaults to the path to the current document location;

      • ; Domain =domain (e.g. ‘example.com’, ‘subdomain.example.com’) if not defined, defaults to the domain part of the path to the current document location. Contrary to the earlier specification, putting a. Character before a domain name will be ignored because browsers may refuse to set such cookies. If a field is specified, subfields are included;

      • ; Max-age =max-age-in-seconds (for example, a year is 60*60*24*365);

      • ; Expires = date-in-gmtString-format If not defined, cookies will expire at the end of the conversation. See date.toutcString () for the format of this value;

      • ; Secure (Cookies are transmitted only through HTTPS);

    • The cookie value string can be guaranteed to not contain any commas, semicolons, or Spaces with encodeURIComponent() (cookie values disallow these values).

  • Modify the cookies:

    document.cookie = nowCookie;
    Copy the code

    Reassigning an existing Cookie overwrites the old value. Note: You need to keep the path and domain values unchanged, otherwise a new cookie will be added.

  • Delete Cookie: Set the expiration time of an existing Cookie name to the past time:

    document.cookie = 'uid=dkfywqkrhkwehf23; expires=' + new Date(0) + '; path=/; secure; '
    Copy the code

Such as:

document.cookie = "yummy_cookie=choco";
document.cookie = "tasty_cookie=strawberry";
console.log(document.cookie);
// logs "yummy_cookie=choco; tasty_cookie=strawberry"
Copy the code

Cookie size and number limits:

Different browsers have different limits on the size and number of cookies. Generally, a maximum of 30 cookies can be set for a single domain name, and the size of each Cookie cannot exceed 4kb. If the size exceeds the threshold, cookies are ignored and will not be set.

The Web SQL:

  • The Web SQL Database API is not part of the HTML5 specification, but it is a separate specification that introduces a set of APIs for manipulating client databases using SQL;
  • Web SQL Database uses SQL to manipulate the client Database apis, which are asynchronous and the SPECIFICATION uses SQLlite (SQL back end);
  • Web SQL Database works in the latest versions of Safari, Chrome, and Opera browsers;
  • Web SQL Database currently has no API for deleting databases and does not support deleting libraries.
  • Once a W3C recommendation, it is now deprecated and should be avoided

Core approach:

  • OpenDatabase (dbName, Version, DESP, size, callback) – Open or create a new database;

    1. dbName: Database name
    2. version: the version number
    3. desp: Description text
    4. size: Database size
    5. callback: creates a callback, which is called after the database is created.
  • Transaction () – Read and write database transactions and commit or rollback execution (the rollback function);

  • ExecuteSql () – Execute the actual SQL query;

Operation database:

// Create database
var db = openDatabase('mydb'.'1.0'.'Test DB'.2 * 1024 * 1024);
// Perform operations on data
db.transaction(function (tx) {
    / / create the TABLE
    tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)'); 
    // Insert fields with dynamic values
    E_id and e_log are external variables in an executeSql instance. ExecuteSql maps each entry in the array parameter to "?"
    tx.executeSql('INSERT INTO LOGS (id,log) VALUES (? ,?) ', [e_id, e_log]);
    // Query the database
    tx.executeSql('SELECT * FROM LOGS'[],function (tx, results) {
        console.log(results);
    }, null);
});
Copy the code

With IndexedDB:

IndexedDB is an underlying API for storing large amounts of structured data (also file/binary Large objects (BloBs)) on the client side. The API uses indexes for high-performance searches of data.

Why IndexedDB is replacing Web SQL:

Web SQL is a true relational database based on SQLite, a lightweight relational database management system that complies with ACID. IndexedDB, on the other hand, is NoSQL (non-relational), uses key-value pairs to store data, and has an unfixed structure, much like pure objects in JavaScript.

“Relational databases” are very strict about consistency, such as 100 data writes, the first 99 succeed, and the 100th is invalid, at which point the transaction is rolled back to its original state. This ensures that the data stored at the end of the transaction is in the same state as the data stored at the beginning. This is ideal for scenarios where banks have high requirements for data consistency. However, this consistency guarantee comes at a performance sacrifice. However, for web2.0 applications such as Weibo and Qzone, consistency is not so important. For example, if friend A sees my homepage and friend B sees my homepage, the information is different. It is not A big deal, but A few seconds difference is OK. While this type of application does not require consistency, it does require performance because reads and writes are so frequent. If you use a “relational database”, the benefits of consistency do not pay off, but the performance problem is more obvious, in this case, not guaranteed consistency but better performance of the “non-relational database” is more appropriate. At the same time, because the data structure of a “non-relational database” is not fixed, it is very easy to expand. With social networking sites, demand changes happen all the time, so adding new fields is inevitable, and “non-relational” databases are easy to use. If you use “relational” databases, you probably need to change the data dramatically, so you need to think about it. Temperamentally, “relational database” is stable and durable, “non-relational database” is quick and clever. On the front end, Web SQL Database is a “relational Database” and indexedDB is a “non-relational Database.”

Web SQL directly write SQL statements, need to convert JS objects into relational string statements; IndexedDB, on the other hand, contains JS objects directly in the database, and implements data addition, deletion, modification and query through API calls.

Overview of Indexed API:

Unlike browser operations on Storage objects, which are synchronous, indexedDB is asynchronous. To get access to the database, call the open() method on the indexedDB property of the Window object. This method returns an IDBRequest object; Asynchronous operations communicate with the calling program by firing events on IDBRequest objects.

  1. Open database:
    window.indexedDB.open(dbName, version);
    Copy the code
    • dbName: database name. If the specified database does not exist, a new database will be created.
    • version: Database version. If omitted, the current version is used by default when an existing database is opened. When creating a database, the default value is1. When we add or modify fields in the database, we need to increase the version.
    let db;
    const idbOpenRequest = indexedDB('testDB'.1);
    idbOpenRequest.onsuccess = function (event) {
      // Database information
      const db = event.target.result;
      // Other processing
    }
    idbOpenRequest.onerror = funtion(event) {
      // Exception handling
    }
    Copy the code
  2. Create primary key and field:
    // This callback is executed when:
    // The first created version of the database, or the new version passed by window.indexeddb.open (with a higher version value than the current version)
    idbOpenRequest.onupgradeneeded = function (event) {
      // Create table
      const objStore = db.createObjectStore('testTable', {
        keyPath: 'id'.autoIncrement: true});// Add a field
      objStore.createIndex('name'.'name', {
        unique: true}); objStore.createIndex('age'.'age');
    }
    Copy the code
  3. Add data:

    Since all database operations are based on transactions, a transaction must be established before adding, deleting, modifying, or querying a database.

    All operations are asynchronous, so callbacks can be added after success or failure.
    // Create transaction
    const transcation = db.transcation(['testTable'].'readwrite');
    // Find the object corresponding to the table
    const objStore = transcation.objectStore('testTable');
    // Add data
    const dbAddRequest = objStore.add({
      name: 'abc'.age: 11}); dbAddRequest.onsuccess =function () {
      console.log('Write succeeded');
    };
    dbAddRequest.onerror = function () {
      console.log('Write failed');
    }
    Copy the code
    • db.transcation(tableName, mode)
      • TableName: data tableName, which can be a string of table names or a string list of multiple table names;
      • Mode: The types of access that can be performed in a transaction, only” readonly” and “readwrite”;
  4. Query data:
    const dbGetRequest = objStore.get(1);
    dbGetRequest.onerror = function () {
      console.log('Transaction failed');
    };
    dbGetRequest.onsuccess = function (event) {
      const data = event.target.result;
      if (data) {
        console.log('Name: ' + data.name);
        console.log('Age: ' + data.age);
      } else {
        console.log('No data record obtained'); }};Copy the code
  5. Delete data:
    const dbDeleteRequest = objStore.delete(1);
    dbDeleteRequest.onsuccess = function () {
      console.log('Deleted successfully');
    }
    dbDeleteRequest.onerror = function () {
      console.log('Delete failed');
    }
    Copy the code
  6. Traversal data:
    const dbGetAllRequest = objStore.openCursor();
    dbGetAllRequest.onsuccess = function (event) {
      const cursor = event.target.result;
    
      if (cursor) {
        console.log('Id: ' + cursor.key);
        console.log('Name: ' + cursor.value.name);
        console.log('Age: ' + cursor.value.age);
        cursor.continue();
      } else {
        console.log('No more data! '); }};Copy the code
  7. Update data:
    const dbPutRequest = objStore.put({
      id: 1.name: 'aaa'.age: 20}); dbPutRequest.onsuccess =function () {
      console.log('Data updated successfully');
    };
    
    dbPutRequest.onerror = function () {
      console.log('Data update failed');
    }
    Copy the code

Note: Like most Web storage solutions, IndexedDB follows the same origin policy. So when you store data in one domain, you can’t store data in another domain.

Trust Tokens:

Trust Tokkens is a privacy-friendly API from Google. In order to completely replace third-party cookies, the new Trust Token API will be replaced by generating unique encrypted signature tokens for each user that the advertiser cannot track. But site owners can still access it to determine whether the user is a robot or a real person.

References:

  • MDN
  • Very complete very complete front-end local storage explanation
  • Cookie attribute details
  • Job interviews are no longer scary: The most complete cookie ever
  • This time I’ll take you through Cookie
  • [HTML5] Web SQL Database [deprecated]
  • HTML5 indexedDB front-end local storage database example tutorial
  • Trust Token API Explainer