In the development of front-end projects, front-end local storage is essential, today xiaobian on the use of front-end local storage in the project in detail. Front-end local storage includes:

  • cookie
  • localStorage
  • sessionStorage
  • webSQL/indexDB

The next several front-end common storage methods are introduced.

cookie

A cookie is a small piece of text stored on the client, whose size cannot exceed 4kb. When requesting an interface, the cookie will be carried by the request and then read and used by the server. Open the browser console, F12>>Application>>Cookies, randomly select a field, we can see there are a lot of Cookies, as follows:


The main properties

  • Name

The name of the cookie

  • Value

The value of cookie, with a maximum size of 4Kb

  • Domain

Domain name for storing cookies

  • Path

Path where the cookie is stored

  • Size

The size of the cookie

  • Expires/Max-Age

These two properties relate to the lifetime of the cookie

Expires attribute specifies a specific expiration time, arrived after the specified time, the browser will no longer keep the cookie, its value is UTC format, you can use the Date. The prototype. ToUTCString () format conversion.

The max-age attribute specifies the number of seconds the cookie will exist from now on, such as 60 * 60 (an hour). After this time, the browser no longer keeps the Cookie.

Max-age has a higher priority than Expires, and if neither is set, the cookie will expire when the browser closes.

  • HttpOnly

If this property is set, it means that the cookie cannot be fetched by JavaScript, preventing the cookie from being read by the script and then carried when the request is made.

  • Secure

This parameter specifies that the browser can send cookies only when the encryption protocol HTTPS is used. The cookie function is automatically enabled when the encryption protocol HTTPS is used.

use

  • Set the cookie
/ * ** setting cookies* @param {*} Key name* @param {*} val value* @param {*} time Expiration time* / export const setCookie = (key, val, time) => {   var date = new Date();   var expiresDays = time;  // Convert the time to the format of the cookie set time  date.setTime(date.getTime() + expiresDays * 24 * 3600 * 1000);   document.cookie = key + "=" + val + "; expires=" + date.toDateString();  } Copy the code
  • To get a cookie
/ * ** get a cookie* @param {*} Key name* /
export const getCookie = (key) => {   var getCookie = document.cookie.replace(/[ ]/g, "");   var arrCookie = getCookie.split(";")   var tips;   for (var i = 0; i < arrCookie.length; i++) {   var arr = arrCookie[i].split("=");   if (key == arr[0]) {   tips = arr[1];   break;   }   }   return tips;  } Copy the code
  • Delete the cookie

To delete the cookie, you can directly call the method of setting the cookie and set the expiration time to -1, as follows:

setCookie(key,' ',-1)
Copy the code

localStorage/sessionStorage

LocalStorage and sessionStorage is in HTML 5 new joining technology, both in addition to data timeliness is different, other are all the same. The size is usually 5MB. When stored, it is only stored on the client and is not transmitted to the server as requests are called.

LocalStorage is valid permanently unless manually deleted. SessionStorage is valid only for the current session

F12>>Application>>Cookies below to see a storage example:


As you can see, it only has two attributes, key and value.

use

LocalStorage and sessionStorage all have the same operation methods, such as setItem, getItem, removeItem, etc. For convenience, we use the secondary encapsulation, as shown in the following example:

  • Memory Storage
/ * ** memory Storage* /export const setStore = (params = {}) => {
  let {
The name, / / nameThe content, / / content type/ / type } = params;  let obj = {  dataType: typeof (content),  content: content,  type: type. datetime: new Date().getTime()  }  if (type) window.sessionStorage.setItem(name, JSON.stringify(obj));  else window.localStorage.setItem(name, JSON.stringify(obj)); } Copy the code
  • Access to Storage
/ * ** Determine whether it is null* /function validatenull (val) {
  if (typeof val === 'boolean') {
 return false  }  if (typeof val === 'number') {  return false  }  if (val instanceof Array) {  if (val.length == 0) return true  } else if (val instanceof Object) {  if (JSON.stringify(val) === '{}') return true  } else {  if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == ' ') return true  return false  }  return false }  / * ** access to Storage* /export const getStore = (params = {}) => {  let { The name, / / nameDebug // Whether to convert the type } = params;  let obj = {},  content;  obj = window.sessionStorage.getItem(name);  if (validatenull(obj)) obj = window.localStorage.getItem(name);  if (validatenull(obj)) return;  try {  obj = JSON.parse(obj);  } catch{  return obj;  }  if (debug) {  return obj;  }  if (obj.dataType == 'string') {  content = obj.content;  } else if (obj.dataType == 'number') {  content = Number(obj.content);  } else if (obj.dataType == 'boolean') {  content = eval(obj.content);  } else if (obj.dataType == 'object') {  content = obj.content;  }  return content; } Copy the code
  • Delete the Storage
/ * ** delete localStorage* /export const removeStore = (params = {}) => {
  let {
 name,  type  } = params;  if (type) {  window.sessionStorage.removeItem(name);  } else {  window.localStorage.removeItem(name);  }  } Copy the code
  • Obtain all Storage
/ * ** Obtain all Storage* /export const getAllStore = (params = {}) => {
  let list = [];
 let {  type  } = params;  if (type) {  for (let i = 0; i <= window.sessionStorage.length; i++) {  list.push({  name: window.sessionStorage.key(i),  content: getStore({  name: window.sessionStorage.key(i),  type: 'session'  })  })  }  } else {  for (let i = 0; i <= window.localStorage.length; i++) {  list.push({  name: window.localStorage.key(i),  content: getStore({  name: window.localStorage.key(i),  })  })   }  }  return list;  } Copy the code
  • Clearing all Storage
/ * ** Empty all Storage* /export const clearStore = (params = {}) => {
  let { type } = params;
 if (type) {  window.sessionStorage.clear();  } else {  window.localStorage.clear()  }  } Copy the code

Cookie, localStorage, sessionStorage similarities and differences

Data storage time

  • Cookies can set their own expiry time
  • If localStorage is not deleted, it is permanently stored
  • SessionStorage Deleted when current page is closed

The size of the

  • Cookie maximum 4 KB
  • LocalStorage the biggest 5 MB
  • SessionStorage the biggest 5 MB

Request whether to carry

  • Cookies are carried in the request header with each request
  • LocalStorage is not carried and is stored only on the client
  • SessionStorage is not carried and is stored only on the client

Ease of use

  • Cookie native API is not friendly to use and requires its own secondary encapsulation
  • The native interface of localStorage can be used, or it can be encapsulated twice by itself
  • SessionStorage native interface can be used, also can own secondary encapsulation

It is recommended to use storage in a project. Too much data stored in cookies may cause performance problems. Of course, you can choose according to the actual situation, the second packaging method has both hands.

webSQL/indexDB

For simple data storage, storage and cookies are enough, but if you need to store more complex relational data, and then use storage and cookies, it is a little inadequate. You can use webSQL or indexDB for storage at this point.

webSQL

The Web SQL database API is a standalone specification that provides native storage of structured data at the browser level and is already supported by many modern browsers.


Core API
  • OpenDatabase () => Open or create a database.
  • Transaction () => This method can control one or more transactions and commit or roll back based on that
  • ExecuteSql () => Is used to execute actual SQL queries
Check whether your browser supports this feature

As you can see from the above figure, webSQL compatibility is not very good, so we need to check whether the browser supports it first.

if (window.openDatabase) {
// Operate web SQL} else {
     alert('Current browser does not support webSQL!! ');
}
Copy the code
WebSQL action class encapsulation

WebSQL operation class encapsulation code is large, here will not show, need partners can pay attention to my public account reply [webSQL operation class] to obtain. Here’s a simple example:

var myDB = {
    name: 'formData'.    version: 1,
    db: null,
};
myDB.db = openDatabase(myDB.name, myDB.version, 'test', 100 * 1024 * 1024); myDB.db.transaction(function(tx) {  tx.executeSql(' '[],function(tx, result) {  if(result.rows.length! = 0) { //result.rows.item(i)  }  }, function(tx, error) {  console.log(error);  }); }) Copy the code

Common SQL statements:

/ / the new table'CREATE TABLE IF NOT EXISTS 表名 (表名 1 PRIMARY KEY, 表名 2 UNIQUE, 表名 3)
/ / delete table'DROP TABLE name '
/ / clear the table'DELETE FROM table name ' // Delete the entry'DELETE FROM table_name WHERE table_name 1 =? And id =? ' // Add a new one'INSERT INTO VALUES (? ,? ,? ,? ,? ,? ,?) '// Add values for all columns'INSERT INTO table name (' 2 ') VALUES (? ,? ,?) '// Adds a value for the specified column// Batch incrementinsert into persons (id_p, lastname , firstName, city ) values (200,'haha' , 'deng' , 'shenzhen'), (201,'haha2' , 'deng' , 'GD'), (202,'haha3' , 'deng' , 'Beijing') // Update one'UPDATE table_name SET table_name 1 =? Where column name 2 =? AND id =? ' 'UPDATE table_name SET table_name 1 =? , column name 2 =? , column name 3 =? Where column name 2 =? AND id =? ' // Update or add a piece of data based on whether the primary key exists or not'replace into VALUES (1, 2, 3, 4, 5) VALUES (? ,? ,? ,? ,?) ' // Search (for more queries, please feel free to combine them according to your own needs)'select * from table_name where table_name 1 =? And select 1 >=? '// General lookup'select * from table_name where table_name 1 =? Or column name 1 >=? '// General lookup 'select * from table_name ORDER BY? '// Specify sort items'select * from table_name ORDER BY? LIMIT 2; '// Find only 2 items that match the condition WHERE column name IS NOT NULL // NOT NULLWHERE column name LIKE"111%"/ / at the beginning of 111WHERE column name LIKE"% 111"/ / at the end of 111WHERE column name LIKE"% 111%"// contains 111WHERE column name NOT LIKE"% 111%"// do not include 111'_a_'// Three digits and the middle letter is a'_a'// Two digits ending with a'a_'// Two digits starting with a WHERE column name GLOB > 111 // greater than 111WHERE column name GLOB >= 111 // Greater than or equal to 111WHERE column name GLOB! = 111 // Not 111 WHERE column name GLOB'111 *'/ / at the beginning of 111WHERE column name IN (25, 27) // value 25 or 27WHERE column name NOT IN (25, 27) // NOT 25 or 27WHERE column name BETWEEN 25 AND 27 // values BETWEEN 25 AND 27WHERE column name IN ('25'.'27') // Note: Do not forget quotes when concatenating SQL / / index'CREATE INDEX IF NOT EXISTS INDEX name on table name (column name 1, column name 2) ' 'DROP INDEX ' Copy the code

indexDB

The IndexedDB standard is HTML5’s official native database solution. It is not intended to replace server-side databases, but is useful in specific scenarios, such as offline applications. IndexedDB is a lightweight NOSQL database that comes with the browser. More efficient than Web Sql, including indexing, transaction processing, and query capabilities.


As you can see from the figure above, indexDB is fairly compatible.

Using indexDB
Create/open a database

First we need to create or open a database object, using the window.indexeddb.open () method as shown in the following example:

var openRequest =window.indexedDB.open(name, version);
var db;
openRequest.onupgradeneeded = function(e) {
  console.log("Upgrading..."); }openRequest.onsuccess = function(e) {
 console.log("Success!");  db = e.target.result; } openRequest.onerror = function(e) {  console.log("Error");  console.dir(e); } Copy the code

The upgradenneeded event is triggered when the database is opened for the first time, followed by the Success event

The open method returns an object (IDBOpenDBRequest) on which the callback function is defined

The callback function takes an event object as an argument, and its target.result property points to the open IndexedDB database

Create an “object repository” for your data

Now that we have our database objects, we also need to create an “object repository” for our data, as shown in the following example:

db.createObjectStore("test", { keyPath: "email" });

db.createObjectStore("test2", { autoIncrement: true });
Copy the code

KeyPath indicates the key name for storing data, and autoIncrement indicates whether to use an automatically incrementing integer as the key name. In general, one of the two attributes is sufficient.

Create a database transaction object

The transaction method is used to create a database transaction. Before you can add data to a database, you must create a database transaction.

The Transaction method returns a transaction object whose objectStore method is used to get the specified object repository.

var transaction = db.transaction(["firstOS"]."readwrite");

var store = transaction.objectStore("firstOS");
Copy the code

The transaction method takes two parameters:

The first argument is an array containing the repository of the objects involved, usually only one;

The second argument is a string representing the type of operation. Readonly and readwrite;

The Transaction method has three events that you can use to define the callback function.

Abort: transaction interruption; Complete b. Error: a transaction error occurs.

transaction.oncomplete = function(event) {
    // some code
};
Copy the code
Operational data

Transaction objects provide apis for manipulating data.

  • Add data add()

Once you have the object repository, you can use the add method to add data to it, as shown in the following example:

var transaction = db.transaction(["firstOS"]."readwrite");
Var store = transaction. The objectStore (" firstOS ");var data = {name: 'monkey'};
var request = store.add(data,1);
request.onerror = function(e) {
 console.log("Error",[e.target.error.name](http://e.target.error.name)); } request.onsuccess = function(e) {  console.log("Data added successfully!"); } Copy the code

The first argument to the add method is the data to be added, and the second argument is the key that corresponds to the data. This code sets the key name of object O to 1. If you set the key name when creating the data warehouse, you can do so without specifying it.

  • Update data put()
var data = { name: 'monkeysoft' };
var request = store.put(data);
Copy the code
  • Read data get()
var request = store.get(key);
Copy the code
  • Delete data delete()
var request = store.delete(key);
Copy the code
  • Clear database clear()
var request = store.clear();
Copy the code
  • OpenCursor ()
var request = store.openCursor();
Copy the code
IndexDB operation class encapsulation

IndexDB operation class contains a large amount of code, so it will not be shown here

The above is my understanding and arrangement of some front-end local storage, if there is a mistake, welcome you to correct, so as not to mistake people’s children ~ hey hey.

I am Monkeysoft, your [three] is monkeysoft creation of the biggest power, if this article has any mistakes and suggestions, welcome to leave a message!

The article continues to update, you can wechat search [little monkey’s Web growth path] pay attention to the public number for the first time to read, after paying attention to the background reply knowledge system, more can receive xiaobian carefully prepared front-end knowledge system, future learning is no longer confused, more can join the technology group exchange and discussion.


Reference: 1, explaining indexDB and encapsulation https://www.jianshu.com/p/136c268b8559

This article is formatted using MDNICE