preface

With the development of Web applications, more application data needs to be stored in users’ local browsers. The traditional cookie storage scheme can no longer meet the requirements of development, and the server storage scheme is a helpless choice. The HTML Web Storage API is an ideal solution. If it is to store complex data, you can use the Web SQL Database API to achieve, you can use SQL statements to complete the storage and query of complex data. This article introduces you to local storage in HTML5.

Knowledge in this chapter

  • Understand the advantages of Web Storage
  • Understand the difference between localStorage and sessionStorage
  • Master how to set and obtain Storage data
  • Master Storage API properties and methods
  • Understand local database Web SQL

Using THE HTML5 Web Storage function, you can store more data on the client side, and you can achieve data sharing or even synchronization in multiple pages.

1. The insufficiency of cookie storage data

Cookies can be used to pass small amounts of data between programmers. For Web applications, cookies are a built-in mechanism for passing text values back and forth between the server and the client. The server can use cookies to track user visits to different pages. Because of its excellent performance, cookies are widely used in current Web applications.

However, cookies still leave much to be desired, mainly in the following aspects.

1. Size limitation

Cookie size is limited to 4KB. In a rich application environment on the Web, big data like files or emails cannot be accepted.

2. Bandwidth limitation

Cookie data is sent back and forth between the server and the browser whenever a request involves cookies. So no matter which page is visited, cookie data will consume network bandwidth.

3. Security risks

Because cookies are frequently transmitted over the network and the data is visible on the network, there is a security risk if they are not encrypted.

4. Complex operation

Manipulating cookie data with JavaScript in the browser on the client side is complicated. But the server can easily manipulate the cookie data

2. Advantages of Using Web Storage

Web Storage can save a large amount of data on the client side, and through the interface it provides, access to data is also very convenient. However, Web Storage was born not to replace cookies, but to make up for the lack of performance of cookies in local Storage. The advantages of local Storage of Web Storage are as follows.

1. Storage capacity

Provides greater storage capacity. In Firefox, Chrome, Safari, and Opera, each domain is 5MB; 10MB in IE8 and above.

2. Zero bandwidth

Web Storage does not occupy bandwidth because it is local Storage and does not interact with the server.

3. Programming interface

Web Storage provides a set of rich programming interfaces, making data operation more convenient

4. Independent storage space

Each domain has an independent storage space, and each storage space is completely independent, so there is no data confusion.

Thus, Web Storage can not completely replace cookie, cookie can do things, Web Storage can not do, such as the server can access cookie data, but can not access Web Storage data. So Web Storage and cookies complement each other and play a role in different areas. With the development of mobile Internet, rich application on browser side is definitely a trend.

3. The difference between sessionStorage and localStorage

Web Storage includes sessionStorage (sessionStorage) and localStorage (localStorage). People familiar with the Web into the first contact with Web Storage, will naturally and session and cookie to correspond. The difference is that cookies and sessions are completely server-side data, while sessionStorage and localStorage are completely browser client data. SessionStorage and localStorage inherit the same Storage API, so the programming interface of sessionStorage and localStorage is the same. The main difference between sessionStorage and localStorage is the time range and page range of the data. SessionStorage: localStorage: sessionStorage: localStorage

4. Check whether the browser supports Web Storage

Code to put on the page:

Function CheckStorageSupport(){if(window.sessionStorage){console.log(" Browser supports sessionStorage! ); }else{console.log(" Browser does not support sessionStorage feature!" ); } if(window.localstorage){console.log(" Browser supports localStorage feature!" ); }else{console.log(" Browser does not support localStorage feature!" ); } } window.addEventListener("load",CheckStorageSupport,false);Copy the code

Console preview results: I will directly enter the console to see the results, readers can put the above code into the page, run to see the results:

5. Set and obtain Storage data

SessionStorage and localStorage, as window properties, fully inherit the Storage API and provide the same methods for manipulating data. The following uses the sessionStorage attribute as an example.

1. Save data to sessionStorage

window.sessionStorage.setItem("key","value");

Key is the Key, value is the value, and setItem() is the method of saving data.

2. Get data from sessionStorage

If you know the key stored in sessionStorage, you can get the corresponding value. The basic syntax for sessionStorage to obtain data is as follows:

value = window.sessionStorage.getItem("key");

3. Set and get other ways of writing data

An even easier way to access Storage objects is to set and get data directly on the sessionStorage object based on the pairing of keys and values, completely avoiding calls to the setItem() and getItem() methods. The method of saving data can also be written as follows.

window.sessionStorage.key = "value";

or

window.sessionStorage["key"]="value";

The method of obtaining data is more straightforward and can be written as follows:

value = window.sessionStorage.key;

or

value = window.sessionStorage["key"]; For localStorage, the above methods of setting data and obtaining data are also available. Code examples:

6. Storage API properties and methods

With sessionStorage and localStorage, all of the above attributes and methods can be used, but be aware of the scope of their influence.

7. Store data of the JSON object

Serialize data in JSON format

Storage stores data in strings. Therefore, before storing JSON data, you need to convert JSON data to strings, which is called serialization. You can serialize jSON-formatted data into string data using json.stringify (). Var stringData = json.stringify (jsonObject);

The above code serializes the json-formatted data object jsonObject into the stringData stringData.

2. Serialize the data to JSON format

If the data in the Storage is accessed as JSON objects, the string data needs to be converted to JSON data, which is called deserialization. You can use json.parse () to deserialize string data into JSON-formatted data. Parse (stringData); var jsonObject = json.parse (stringData);

This code deserializes the stringData stringData into a json-formatted data object, jsonObject. Json.parse () only deserializes jSON-formatted string data. If the string data does not conform to the JSON format, the eval() function can be used to deserialize jSON-formatted string data. Errors are generated and security risks are reduced, but the eval() function is much faster to execute in terms of efficiency. Code examples:

Sometimes, multiple web pages or tabs can access Storage data at the same time. In order to ensure that the modified data can be timely feedback to another page, HTML5 Web Storage to establish a set of event notification mechanism, will be triggered when the data update. The Web Storage event is triggered if the listening window is cognate of the window that performed the Storage, regardless of whether the listening window stored data. For example, the following code, after adding listening events, can receive the same origin window Storage events. window.addEventListener(“storage”,EventHandle,true); Storage is added to the listening event, as long as the same Storage event occurs, can be due to data update and start the event. The interface of the Storage event is as follows:

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

The StorageEvent object, which is passed to the event handler when the event is triggered, contains all the information necessary to store the change. Storage event attributes:

9. Local database Web SQL

To further enhance the storage capability of the client, HTML5 introduces the concept of a local database. The specification for Web SQL Database uses the SQLite Database, which allows applications to access the Database through an asynchronous JavaScript interface. SQLite is a lightweight database, ACID-compliant relational database management system that has the advantage of being embedded and requiring only a few hundred KILobytes of memory. In the aspect of cross-platform, it can support Windows, Linux and other mainstream operating systems, and can be combined with many programming languages such as C#, PHP, Java, JavaScript and so on. It includes an ODBC interface and is also quite impressive in terms of speed. There are three core methods defined in the Web SQL Database specification:

###10. Web SQL database basic operations

1. Open the database

Var db=openDatabase("TestDB","1.0"," TestDB", 2*1024*1024,creation Callback);

This method takes five required parameters: the first parameter indicates the database name, the second parameter indicates the version number, the third parameter indicates the description of the database, the fourth parameter indicates the size of the database, and the fifth parameter indicates the creation of the callback function, of which the fifth parameter is optional.

2. Create a database

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

The tx passed to the callback function using the transaction() method is a transaction object, and the executeSql() method of that transaction object can be used to executeSql statements, which in this case are commands to create data tables.

3, add data to database table

Db. Transaction (function(tx){tx.executeSql('INSERT INTO UserName(id,name) VALUES(1," 三")); ExecuteSql ('INSERT INTO UserName(id,name) VALUES(2," 三 ")'); });Copy the code

Two SQL statements containing the Insert INTO command to Insert data will add two data to the UserName table in the local database TestDB.

4. Read the data in the database

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

The executeSql() method executes an SQL statement containing the select command, which represents a query, and queries information from the UserName table in the TestDB local database. The results of the query are passed to anonymous callback functions where the results of the query, such as console output, can be processed.

The above article hopes to be helpful to everyone.