Local storage refers to storing data in a browser, as opposed to a server.

1. Classification of local storage

There are four types of local Storage: Cookie, Storage, SQL database, and IndexedDB.

Cookie

Cookie was first proposed. It was originally designed only to store users’ login information, so it was not suitable for storing large amounts of data. Cookie has a small capacity. It splices the saved data into strings and operates with the program. If a url is not opened, the browser will send all Cookie data from that site to the server, because it was originally designed only to protect the user’s login information (such as SessionId).

Storage

Sotrage is an HTML5 object for storing local data, and because it’s designed to store local data, it’s much more flexible than cookies. Storage has a larger capacity than Cookie. You can directly store data by key/value pair and obtain data using key names. Storage is divided into sessionStorage and localStorage, the former will be cleared after the browser closed, the latter will always be stored in the browser, unless manual or code removal.

SQL database

The SQL database encapsulates a small SQLLite database in the browser, but is not suitable for use from the front-end architecture. For example: JS object attributes may change at any time, may be added or deleted, may also change the data type, but SQL database requires that the data before the operation of the data to determine the structure of the data.

IndexedDB

IndexedDB is a noSQL database that is unstructured and holds data records that can change properties (fields) at any time, just like JS objects. Compared with Storage, it can hold more data, and can also use the database index, transaction and other related concepts, but it is more complex than Storage.

2. Storage to store

Storage is a function property object of window object, but this function object is special, it can not be used as a method to execute, also can not be used to create instance object, JS engine will default to create two Storage instance object, directly call can be. The two Storage instances created by the JS engine are sessionStorage and localStorage. The former is used for temporary Storage, and the data will be lost after the browser is closed. The latter is used for long-term storage, and data is not lost when the browser is closed. Storage.prototype:Methods of manipulating data include:

  • getItem(key)
  • setItem(key, value)
  • removeItem(key)
  • clear()

Set a value in the console using session Storage setItem to view it in the Application session Storage:

LocalStorage and sessionStorage are used in the same way, the difference is in the way of data removal after storage.

3. StorageEvent

Modify data Storage instance objects will trigger a StorageEvent event, some special this event, after the event is triggered, the message will be sent to all currently open web site other pages (to) in the same browser, of course, as to whether or not will be sent to the current page, different browsers and different processing methods. (In my test, the following browsers behave the same and do not send to the current page: Google Chrome (85.0.4183.83), (Microsoft Edge 44.18362.449.0), Firefox (78.0.2 (64-bit), Dual-core Browser (version 1.0.4.2))

Code examples:

<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial =1.0"> <title>Document</title> </head> <body> <input value="Test Storage" type="button" id='button'/> <script> const btn = document.querySelector('#button'); btn.onclick = () => { localStorage.setItem('testKey', 'testValue1'); } window.addEventListener('storage', function(e){ console.log(`key: ${e.key}`); console.log(`oldValue: ${e.oldValue}`); console.log(`newValue: ${e.newValue}`); console.log(`url: ${e.url}`); console.log(`is localStorage: ${e.storageArea === localStorage}`); }); </script> </body> </html>Copy the code

4. Introduction to IndexedDB database

IndexedDB is a noSQL database, but the concepts used are mostly similar to THOSE used in SQL databases, although there are some differences. The only difference is that the IndexedDB database does not convert objects into records and then store them in tables, but instead stores objects directly, using the “ID-> Data Objects” schema.

IndexedDB Database operation

There are 11 main objects associated with an IndexedDB database: IDBFactory, IDBDatabase, IDBObjectStore, IDBIndex, IDBKeyRange, IDBCursor, IDBCursorWithValue, IDBTransaction, IDBVersionChangeE Vent, IDBOpenDBRequest, and IDBRequest. These 11 objects are window property objects of type function. They are used as examples, but do not need to be created by the user using new. They can be obtained automatically when needed. The 11 objects can be divided into four categories: database and ObjecStore-related objects, data-related objects, query-related objects, and auxiliary objects. Cylinder auxiliary objects include IDBVersionChangeEvent, IDBOpenDBRequest and IDBRequest.

Operations related to the database and ObjectStore
  1. Create/open the database

IndexedDB database operations are event-based, or asynchronously processed. The open needed method returns an IDBOpenDBRequest power object with common attributes such as ONSuccess, onError and onupgradeneneeded, which represents successful opening, failed opening and database version upgrade, respectively.

Grammar:

const db_worker = indexedDB.open('dbName', dbVersion);
Copy the code

Example:

<script> const workerDBRequest = indexedDB.open('database', 1); Workerdbrequest. onError = function(event) {console.log(' failed to open database '); } workerDBRequest.onsuccess = function(event) { db_worker = workerDBRequest.result; // You can also use event.target.result console.log(' opened successfully '); } </script>Copy the code

  1. Create the ObjectStore

Indexeddb.open () returns an IDBOpenDBRequest object. The result of IDBOpenDBRequest is an IDBDatabase object with which ObjectStore can be created. This result contains the following attribute methods:CreateObjectStore and deleteObjectStore are used to create and deleteObjectStore respectively.

Note: createObjectStore, deleteObjectStore can only be executed in the onupgradenneeded method.

The createObjectStore method takes two parameters. The first parameter is the name of the ObjectSore to be created, and the second parameter is an object describing the ID. This object can have two properties: KeyPath and autoIncrement, the former used to specify an attribute in an object as an ID, and the latter, when true, generates an ID with a Generator when saving data, but you need to create a Generator yourself. The following is an example:

<script> const workerDBRequest = indexedDB.open('worker', 2); Workerdbrequest. onError = function(event) {console.log(' failed to open database '); } workerDBRequest.onsuccess = function(event) { db_worker = workerDBRequest.result; // You can also use event.target.result console.log(' database opened successfully '); } workerDBRequest.onupgradeneeded = function(e) { var db = workerDBRequest.result; db.createObjectStore('category', {}); Console. log(' ${db.name} 'version number changed to ${db.version}'); } </script>Copy the code
Data operation correlation

Data-related operations, in addition to those described previously, mainly use IDBTransaction objects that represent transactions. Most operations in the database (the instance object of IDBDatabse) are performed using transactions. The database instance object contains a transaction method property (the property of idbDatabase.prototype in real time) that is invoked to create a transaction. The transaction method takes two parameters. The first parameter specifies the ObjectStore to operate on. The first parameter can be one or multiple objectStores. The second parameter specifies the type of transaction, which can be readonly(the default) or readwrite to create a read-only or read-write transaction, respectively.

Attributes contained in an IDBTransaction instance:

[“objectStoreNames”, “mode”, “db”, “error”, “onabort”, “oncomplete”, “onerror”, “objectStore”, “commit”, “abort”, “durability”, “constructor”]

The IDBObjectStore instance contains the following attributes:

[“name”, “keyPath”, “indexNames”, “transaction”, “autoIncrement”, “put”, “add”, “delete”, “clear”, “get”, “getKey”, “getAll”, “getAllKeys”, “count”, “openCursor”, “openKeyCursor”, “index”, “createIndex”, “deleteIndex”, “constructor”]

Increase the data

Example:

<script> const workerDBRequest = indexedDB.open('worker', 3); Workerdbrequest. onError = function(event) {console.log(' failed to open database '); } workerDBRequest.onupgradeneeded = function(e) { var db = workerDBRequest.result; db.createObjectStore('category', {keyPath: 'id'}); Console. log(' ${db.name} 'version number changed to ${db.version}'); } workerDBRequest.onsuccess = function(event) { db_worker = workerDBRequest.result; // You can also use event.target.result console.log(' database opened successfully '); workerDBOpenSuccess(); } function workerDBOpenSuccess() { const tx_category = db_worker.transaction('category', 'readwrite'); const store_category = tx_category.objectStore('category'); const category1 = {'id':007, 'name':'zzh', 'age':18}; const categoryAddRequest = store_category.add(category1); CategoryAddRequest. Onsuccess = function (event) {the console. The log (' save success); {} categoryAddRequest. Onerror = function (evevt). The console log (" save failed "); } } </script>Copy the code

Query data

Example:

<script> const workerDBRequest = indexedDB.open('worker', 3); Workerdbrequest. onError = function(event) {console.log(' failed to open database '); } workerDBRequest.onupgradeneeded = function(e) { var db = workerDBRequest.result; db.createObjectStore('category', {keyPath: 'id'}); Console. log(' ${db.name} 'version number changed to ${db.version}'); } workerDBRequest.onsuccess = function(event) { db_worker = workerDBRequest.result; // You can also use event.target.result console.log(' database opened successfully '); workerDBOpenSuccess(); } function workerDBOpenSuccess() { const tx_category = db_worker.transaction('category', 'readwrite'); const store_category = tx_category.objectStore('category'); const categoryGetRequest = store_category.get(7); CategoryGetRequest. Onsuccess = function (event) {the console. The log (` query success: ${JSON. Stringify (categoryGetRequest. Result)} `); } } </script>Copy the code

There are many other ways to query, and just like a relational database, queries can filter data based on different criteria.

Modify the data
<script> const workerDBRequest = indexedDB.open('worker', 3); Workerdbrequest. onError = function (event) {console.log(' failed to open database '); } workerDBRequest.onupgradeneeded = function (e) { var db = workerDBRequest.result; db.createObjectStore('category', { keyPath: 'id' }); Console. log(' ${db.name} 'version number changed to ${db.version}'); } workerDBRequest.onsuccess = function (event) { db_worker = workerDBRequest.result; // You can also use event.target.result console.log(' database opened successfully '); workerDBOpenSuccess(); } function workerDBOpenSuccess() { const tx_category = db_worker.transaction('category', 'readwrite'); const store_category = tx_category.objectStore('category'); const categoryGetRequest = store_category.get(7); CategoryGetRequest. Onsuccess = function (event) {the console. The log (` query success: ${JSON. Stringify (categoryGetRequest. Result)} `); let data = event.target.result; data.age = 19; const categoryPutRequest = store_category.put(data); CategoryPutRequest. Onsuccess = function (event) {the console. The log (' updated '); } } } </script>Copy the code

IndexedDB may not update the display in real time and may need to be refreshed to view the actual value.

Delete the data

Example:

<script> const workerDBRequest = indexedDB.open('worker', 3); Workerdbrequest. onError = function (event) {console.log(' failed to open database '); } workerDBRequest.onupgradeneeded = function (e) { var db = workerDBRequest.result; db.createObjectStore('category', { keyPath: 'id' }); Console. log(' ${db.name} 'version number changed to ${db.version}'); } workerDBRequest.onsuccess = function (event) { db_worker = workerDBRequest.result; // You can also use event.target.result console.log(' database opened successfully '); workerDBOpenSuccess(); } function workerDBOpenSuccess() { const tx_category = db_worker.transaction('category', 'readwrite'); const store_category = tx_category.objectStore('category'); const categoryDeleteRequest = store_category.delete(7); / / delete categoryDeleteRequest by id. Onsuccess = function (event) {the console. The log (' delete 'success); } } </script>Copy the code

The display needs to be refreshed before viewing.

There is more to IndexedDB, so first understand the noSQL principles and then understand the objects and the operations that can be performed on them. Interested also can refer to MDN details: developer.mozilla.org/zh-CN/docs/…

I would be honored if this article could be of any help to you. It would be a great honor if the article was liked by you.

Personal wechat: iotzzh Public account: front-end wechat personal website: www.iotzzh.com