Two storage systemsInitially, the Network was considered as a means of displaying static information. Data processing was taken up later: first with the help of server applications, and then also with the use of inefficient scripts and embedded modules on user computers. Nevertheless, the essence of the processes remained unchanged: the data were prepared on the server and only after that were displayed on the user's computer. Hard work was almost always done on the server side, as the system did not have the capacity to use the resources of the client computer.
Thanks to the HTML5 specification, the situation has been balanced. Focusing on the features of mobile devices, the emergence of cloud computing and the need to standardize technologies and innovations that have been introduced over the years through embedded modules, the HTML5 developers have combined in one specification all the functionality that allows them to run full-fledged applications on the client side.
One of the most demanded features of any application is data storage and access to them as needed, but web applications did not have an effective mechanism to do this. On the client side, cookies were used to store small amounts of information, but their nature is such that they support the recording of only short lines and are far from convenient to use them in all situations.
The Web Storage API (Web Storage) is essentially the next step in the development of cookies. This API allows you to write data to the user's hard disk and access them in the same way as is done in desktop applications. The data storage and retrieval processes supported by this API are applicable in two situations: when information should be available only for one session and when it needs to be stored for a long time - until the user deletes it. Thus, to simplify the life of developers, this API was divided into two parts - sessionStorage and localStorage:
- sessionStorage. This is a storage engine that holds data only for a single page session. In fact, unlike real sessions, we are talking about information that only one browser window or tab has access to, and as soon as a window or tab is closed, this information is deleted. In the specification, the term “session” is used, since the information is preserved even when the window contents are updated, as well as in the case when the user opens a new page on the same website;
- localStorage. This mechanism works similarly to storage systems for desktop applications. Data is recorded forever, and the application that saved it can access this information at any time.
Both mechanisms work through the same interface and offer the same methods and properties. In addition, both mechanisms are tied to the source, that is, any information in the repository is available only through the website that created it. Each website has its own storage space, which, depending on the mechanism used, is cleared when the window is closed or never cleared.
In this API, there is a clear distinction between temporal and permanent data, which makes it much easier to design both small applications that require temporary storage of only a few lines (for example, the contents of a cart in an online store), and large and complex applications that often save indefinitely entire documents.
sessionStorageThe first component of the API, sessionStorage, replaces session cookies. Cookies, like sessionStorage, store data for a limited time. However, if cookies are tied to a browser, then sessionStorage objects are tied to specific windows or tabs. This means that cookies created for a particular session can be accessed as long as at least one browser window is open, but the data created by sessionStorage is available only until the window is closed (and only specific window or tab can access them). ).
Data storage implementationSince both systems, sessionStorage and localStorage, work with the same interface, one HTML document and a simple form will be enough for us to test code examples and experiment with the API.
14.1. HTML document for storage API<!DOCTYPE html> <html lang="ru"> <head> <title>API -</title> <link rel="stylesheet" href="storage.css"> <script src="storage.js"></script> </head> <body> <section id="formbox"> <form name="form"> <label for="keyword">Keyword: </label><br> <input type="text" name="keyword" id="keyword"><br> <label for="text">Value: </label><br> <textarea name="text" id="text"></textarea><br> <input type="button" id="save" value="Save"> </form> </section> <section id="databox"> </section> </body> </html>
We also created a simple set of styles for the page design, thanks to which the form area will be visually separated from the field for displaying data.
14.2. Block styles #formbox{ float: left; padding: 20px; border: 1px solid #999999; } #databox{ float: left; width: 400px; margin-left: 20px; padding: 20px; border: 1px solid #999999; } #keyword, #text{ width: 200px; } #databox > div{ padding: 5px; border-bottom: 1px solid #999999; }
Data creationBoth sessionStorage and localStorage store data in the form of separate records. A record is considered to be a pair of a keyword and a value, with each value being converted to a string before being placed in the repository. You can think of records as variables with a name and a value that you can create, modify, and delete.
Two new methods are used for creating records and retrieving them from storage space. They are used only in this API:
- setItem (key, value). To create a record, you need to call this method. An entry is created with the keyword and value passed as method arguments. If the repository already has an entry with such a keyword, then a new value is assigned to it, so this method allows you to modify the data;
- getItem (key). To retrieve a value from the repository, you must call this method, passing it the keyword of the desired entry. The keyword must match the one that was declared when the item was created using the setItem () method.
14.3. Saving and retrieving data function initiate(){ var button = document.getElementById('save'); button.addEventListener('click', newitem); } function newitem(){ var keyword = document.getElementById('keyword').value; var value = document.getElementById('text').value; sessionStorage.setItem(keyword, value); show(keyword); } function show(keyword){ var databox = document.getElementById('databox'); var value = sessionStorage.getItem(keyword); databox.innerHTML = '<div>' + keyword + ' - ' + value + '</div>'; } addEventListener('load', initiate);
The process is extremely simple. These methods are included in the sessionStorage object, and the syntax for calling them is always the same: sessionStorage.method (). In the code in Listing 14.3, the newitem () function is executed each time the user clicks the Save button on the form. This function creates an entry and adds the information received from the form to it, and then calls the show () function. In this second function, the entry is retrieved using the getItem () method and the value of the keyword argument. Then the contents of the record is inserted into the databox element and displayed on the screen.
In addition to these methods, the storage API provides a simplified way to create records as well as retrieve them from storage. In this method, you can use the write keyword as a property of the sessionStorage object and thus obtain the value of the record. There are two syntax options for this method: you can enclose the variable storing the keyword in square brackets (for example, sessionStorage [keyword] = value), or you can use a point to access the recording (for example, sessionStorage.myitem = value).
14.4. Work with records in a simplified way. function initiate(){ var button = document.getElementById('save'); button.addEventListener('click', newitem); } function newitem(){ var keyword = document.getElementById('keyword').value; var value = document.getElementById('text').value; sessionStorage[keyword] = value; show(keyword); } function show(keyword){ var databox = document.getElementById('databox'); var value = sessionStorage[keyword]; databox.innerHTML = '<div>' + keyword + ' - ' + value + '</div>'; } addEventListener('load', initiate);
Data deletionRecords can be created, read and, of course, deleted from storage. Two methods are used to perform the latter task:
- removeItem (key). Deletes one entry. To identify an element, the method needs to pass the keyword that was used in the setItem () method when creating a record;
- clear (). Clears storage space. All records in it are deleted.
14.6. Deleting records function initiate(){ var button = document.getElementById('save'); button.addEventListener('click', newitem); show(); } function newitem(){ var keyword = document.getElementById('keyword').value; var value = document.getElementById('text').value;