Hello everyone, I’m Nezha. Nice to meet you ~~

Nezha’s life creed: If you like what you learn, there will be strong motivation to support it.

Learn programming every day, so that you can get a step away from your dream. Thank you for not living up to every programmer who loves programming. No matter how strange the knowledge point is, work with me to calm down the wandering heart and keep going. Welcome to follow me vx:xiaoda0423, welcome to like, favorites and comments

Don’t be afraid to dream, but don’t just dream. Be a doer, not a talker.

preface

If this article is helpful to you, ❤️ follow + like ❤️ encourage the author, accept the challenge? Article public account launch, concern programmer Doraemon first time access to the latest article

Ink ❤ ️ ~

knowledge

Using THE HTML5 Web Storage API, you can store more data on the client side, and can realize data sharing or even synchronization in multiple pages. For complex data, you can use the Web SQL Database API to achieve.

Master the storage methods of localStorage and sessionStorage, store JSON object data, and use the basic operations of Web SQL Database.

Web Storage

Properties, methods, and events of the Web Storage API.

Cookies can be used to pass small amounts of data, and are a built-in mechanism for sending text values back and forth between the server and the client. The server can track the user’s access to different pages based on cookies.

Cookie features:

First, the size of the cookie is limited to 4KB.

Second, the bandwidth is limited. Cookie data will be transmitted back and forth between the server and the browser, so any page visited will consume the bandwidth of the network.

Third, security risks, because cookies will be frequently transmitted over the network, so they are visible on the network, without encryption, is a security risk.

Fourth, the operation is complicated. In the browser of the client, it is quite complicated to operate the cookie data with JavaScript.

Therefore, the existence of cookies only makes sense if small data needs to be transmitted frequently between the server and the client.

What is Web Storage

Web Storage can save a large amount of data on the client. Advantages of Web Storage local Storage:

First, large storage capacity.

Second, zero bandwidth. Data in a Web Storage is stored locally and does not interact with the server. Therefore, network bandwidth is not occupied.

Third, programming interfaces. Provides a set of rich interface, makes the data operation more convenient.

Fourth, independent storage space. Each domain has an independent storage space. Each storage space can be completely independent without causing data chaos.

LocalStorage and sessionStorage

LocalStorage in Web Storage includes sessionStorage sessionStorage and localStorage localStorage.

Cookie and session are data that can be operated by the server, sessionStorage and localStorage are data that can be operated by the browser.

Cookies and sessions inherit the same Storage API, so the programming interfaces of sessionStorage and localStorage are the same.

SessionStorage differs from locatlStorage in the time range and page range of data.

SessionStorage: Data is only saved until the window or tag in which it was stored is closed, and data is also visible within the window or tag in which they were built

LocalStorage: The lifetime of data is longer than the lifetime of a window or browser, and data can be shared by each window or TAB of the same origin.

Check whether Web Storage is supported

Example:

Function CheckStorageSupport() {// Check sessionStorage if(window.sessionStorage) {console.log(" browser supports sessionStorage "); }else{console.log(" Browser does not support sessionStorage"); } // Monitor localStorage if(window.localstorage) {console.log(" Browser supports localStorage"); }else {console.log(" browser does not support localStorage"); }}Copy the code

Set and obtain Storage data

Save data to sessionStorage:

Window. The sessionStorage. SetItem (" key ", "value");Copy the code

SetItem () indicates the method of saving data

Get data from sessionStorage:

value = window.sessionStorage.getItem("key");
Copy the code

GetItem () is the method to obtain data

Save data:

window.sessionStorage.key = "value";
Copy the code

or

window.sessionStorage["key"] = "value"
Copy the code

The method of obtaining data is more straightforward:

value = window.sessionStorage.key;
Copy the code

or

value = window.sessionStorage["key"]
Copy the code

Use sessionStorage and localStorage

Example:

function DaDa() { window.localStorage.setItem("localKey", "localVlaue"); / / get the console. The log (Windows. LocalStorage. The getItem (" localKey ")); window.sessionStorage.setItem("sessionKey", "sessionValue"); / / get the console. The log (window. The sessionStorage. The getItem (" sessionKey ")); }Copy the code

Storage interface

Example:

interface Storage{
 readonly attribute unsigned long length;
 DOMString ? key(unsigned long index);
 getter DOMString getItem(DOMString key);
 setter creator void setItem(DOMString key, DOMString value);
 deleter void removeItem(DOMString key);
 void clear();
}
Copy the code
  1. lengthProperty that represents the currentstorageThe number of key/value pairs stored in an object.

Storage objects are cognate, and the length attribute reflects only the number of cognate key/value pairs

  1. The key method gets the key at the specified position.

  2. GetItem method that returns the corresponding data value based on the key.

  3. The setItem method stores data at the location of the specified key.

  4. The removeItem method removes the specified key/value pair from the stored object.

  5. The clear method clears all data in a Storage object. If the Storage object is empty, no operation is performed.

Use a Storage object to save the content of the page

Example:

SessionStorage function SaveStorage(FRM) {var storage = window.sessionStorage; storage.setItem("name",frm.name.value); storage.setItem("age", frm.age.value); Function Show(){var storage = window.sessionstorage var result = ""; for(var i=0; i<storage.length; i++){ var key = storage.key(i); var value = storage.getItem(key); result += key + ":" + value + ";" ; }}Copy the code

Stores data for JSON objects

Storage stores data as strings. Therefore, before storing JSON data, you need to convert JSON data to strings. This operation is called serialization.

Serialize jSON-formatted data to string data using json.stringify () :

var dada = JSON.stringify(jsonObject);
Copy the code

Deserialize data to JSON format:

var jsonObject = JSON.parse(stringData);
Copy the code

Web Storage to establish a set of events triggered when data update notification mechanism, regardless of whether the monitoring window stored the data, as long as the execution of the Storage window is cognate, will trigger the Web Storage event.

window.addEventListener("storage", EventHandle, true);
Copy the code

StorageEvent Event interface:

interface StorageEvent:Event {
 readonly attribute DOMString key;
 readonly attribute DOMString ? oldValue;
 readonly attribute DOMString ? newValue;
 readonly attribute DOMString ? url;
 readonly attribute Storage? storageArea;
}
Copy the code

Key property: contains the key whose store is always updated or deleted; OldValue property: contains the data corresponding to the pre-update key.

NewValue property: contains updated data; Url property: Indicates the source of the Storage event.

StorageArea property: This property is a reference to the localStorage or sessionStorage whose value has changed.

web SQL Database

Web SQL Database uses an SQLite Database and allows applications to access the Database through an asynchronous JavaScript interface. SQLite is a lightweight database.

  1. openDatabase()Method to create a database object using an existing database or a new database.
  2. transaction()Method that allows the designer to control the commit or rollback of a transaction.
  3. executeSql()Method to execute real SQL queries.

Operate the Web SQL database

Var db = openDatabase("TestDB", "1.0", "TestDB", XXXX)Copy the code

A total of 5 parameters:

  1. The database name
  2. The version number
  3. Database Description
  4. Database size
  5. Create the callback function

Create table

The transaction() method is used for transaction processing, and the executeSql() method is used to executeSql statements.

Create table;

db.transaction(function (tx) {
 tx.executeSql('CREATE TABLE IF NOT EXISTS UserName (id unique, Name)');
});
Copy the code

The TX that the Transaction () method passes to the callback function is a Transaction object, and SQL statements can be executed using the Transaction object’s executeSql() method.

Adding data to a data table:

db.transaction(function (tx){
 tx.executeSql('INSERT INTO UserName (id,Name) VALUES(1,'dada'));
 tx.executeSql('INSERT INTO UserName (id,Name) VALUES (2,'dadada'));
});
Copy the code

Read data from a database:

db.transaction(function (tx){
 tx.executeSql('SELECT * FROM UserName', [], function(tx, resultes){
  var len = results.rows.length;
  for (var i=0; i<len; i++){
   console.log(results.rows.item(i).Name);
  }
 },null);
});
Copy the code

Html5 several storage forms

  1. Local storage –localStorage, sessionStorage
  2. Offline cachingapplication cache
  3. With indexedDB and webSQL

LocalStorage and sessionStorage

  • localStoragePermanent storage, never invalid unless manually deleted
  • sessionStorageWhen the browser opened again, it disappeared

Size, each domain name is 5M, cookie is limited by size, about 4K, second, Internet Explorer 6 domain name is limited.

HTML API

There are two apis in the browser, localStorage and sessionStorage

In the Window object, localStorage corresponds to window.localStorage and sessionStorage corresponds to window.sessionStorage.

As long as localStorage uses the same protocol, host name, and port, it can read or modify data of the same localStorage.

SessionStorage is stricter than localStorage. In addition to protocol, host name, and port, sessionStorage must be in the same window

Methods and Meanings:

SetItem (' key ', 'value') Stores data getItem(' key ') reads data removeItem(' key ') Deletes data Clear () Clears dataCopy the code

How to use:

/ / store data window. Localstage. SetItem (' key ', 'value') / / key: the name of the data / / value: Data / / stored data must be a string type / / read the data window. Localstage. The getItem (' key ') / / key: / / if the name of the data does not exist, return null (generally use it to do judgment) / / delete data window. Localstage. RemoveItem (' key ') / / key: Data name // Delete specified data in local storage // Clear data window.localstage.clear() // Clear all data in local storageCopy the code

LocalStorage and sessionStorage

LocalStorage (long-term storage) and sessionStorage(sessionStorage) are the two interfaces provided by the local web storage in H5. They are equivalent to a small local database in the front end. They are used to store some insensitive data locally and belong to window objects.

What’s the difference between localStorage and sessionStorage?

Similarities: The apis are identical and both store data on the browser side.

Difference:

  1. The data stored in localStorage is permanent data. The page is refreshed. The data is not lost even after the browser restarts or even the operating system restarts.

  2. SessionStorage stores a bit of demanding data, page refresh still works, and data is lost when tabs are closed. However, data can be shared between multiple IFrames that open on the same TAB (in the case of homology).

Both store data in the browser. Data stored in localStorage is limited to the same source and can be communicated across Windows, but not across browsers and domains. SessionStorage stores data that is restricted to tabs (page card closing is lost).

The limitations of localStorage

Limitations:

1. The supported size varies from browser to browser. In the industry, the supported size is 5M

2. Data in localStorage cannot be captured by crawlers

The recent recommendation

  • Drag and drop in HTML5
  • Vue.js pen test questions Solve common business problems
  • Dada front-end personal Web share 92 JavaScript interview questions with additional answers
  • 【 Mind Mapping 】 Front-end development – consolidate your JavaScript knowledge
  • [Illustrated, like collection oh!] Re-study to reinforce your Vuejs knowledge
  • Connect liver 7 evening, summed up the knowledge point of computer network! (66 items in total)

❤️ follow + like + favorites + comments + forward ❤️, original is not easy, encourage the author to create better articles

Likes, favorites and comments

I’m Jeskson, thanks for your talent: likes, favorites and comments, and we’ll see you next time! ☞ Thank you for learning with me.

See you next time!

This article is constantly updated. You can search “Programmer Doraemon” on wechat to read it for the first time, and reply [information] there are materials of first-line big factories prepared by me, which have been included in this article www.dadaqianduan.cn/#/

Star: github.com/webVueBlog/…