Introduction to HTML5 storage APIs

Source: Internet
Author: User
Tags web database sessionstorage
Document directory
  • Prerequisites:
  • The following products are required:
HTML5 storage API introduction Source: infoq Release Date: Reading: 265 full screen reading of the original article link [favorites] Abstract: one of the most interesting features of HTML5 is the ability to locally store data and allow applications to run offline. There are three APIs for processing these functions. This article will introduce you to these three APIs.

One of the most interesting features of HTML5 is the ability to locally store data and allow applications to run offline. There are three different APIs for processing these functions. selecting one of them depends on how you want to process the data you want to locally store:

  • Web storage: Suitable for basic local storage with key/value pairs
  • Offline storage: Use a manifest file to cache all files for offline use.
  • Web Database: Suitable for relational database storage
Prerequisites required:

Be familiar with the online and offline data storage technologies of JavaScript.

The following products are required:

Dreamweaver

Web storage API

The most basic method for local storage on a user's machine is to use the Web storage API. Use this APIKey/valueTo support developers to storeWebBasic information and variables for application access. An ideal use case for this feature is to store simple data that needs to be permanently retained after the user has browsed and left the application or has disabled the web browser. For example, save the game status, save the navigation location, or store some specific information (such as the user name or name) that you want to use in the whole Web application but you do not want to use cookies ). Similar APIs can also be used to store data for individual sessions. The data is automatically cleared after the user browses the application or closes the browser.

When usingWebStorageAPIYou need to remember the following:

  • This storage operation can only be applied to related domains (domain-wide). Therefore, when you use the Web storage function to save data, only other websites in this domain can access the data.
  • The size limit for storing data is about 5 MB. The limit of 5 MB bytes is recommended by W3C *, but this specification provides some reserved space for implementation details. Therefore, the actual byte size depends on the vendor of Each browser.
Check the browser support function

The first thing you need to do before using the Web storage API is to check whether your browser supports this API:

function checkLocalStorageSupport() {
try {
return'localStorage'in window && window['localStorage'] !==null;
} catch (e) {
returnfalse;
}}

You may see in the code snippet above that web storage uses an object named localstorage, which is a windowclass object. The code snippet above can check whether localstorage is actually a window-based object and whether it returns true, so that the application can make full use of the local storage API.

Add and return data

Adding and returning data from localstorage objects is as simple as calling the getter and setter methods implemented by local storage specifications. Localstorage can store any type of data, but all data must be stored in the corresponding storage area in string format. This means that it is necessary to parse the data before it is sent to localstorage or after it is used. For example, to store a JavaScript Object, you must use JSON and call stringify () before retrieving data, and call parse () After retrieving data (). After retrieving numeric variables from the localstorage object, the same is true for parsing them.

In this example, a single form input has been created, so that when you click submit, the corresponding data will be stored in the local high-speed cache area. When a page is loaded, if the data is stored, the page displays the stored information in a welcome window. The following functions are called when you click submit:

function onClick(){
if(checkLocalStorageSupport)
{
window.localStorage.setItem("name",document.getElementById("name").value);
}} 

This function uses the setitem method in the localstorage object, and then uses the values in the corresponding form to fill the storage cache. When a page is loaded, the application uses an onload function to check whether the corresponding data is already in the local cache and adds a welcome window.

function onLoad(){
if(checkLocalStorageSupport)
{
var name = window.localStorage.getItem("name");
if(name !=null)
{
window.document.getElementById("divName").innerHTML ="Welcome back "+ name;
}
}}  
Clear Data

Although users can use a browser to delete localstorage data at any time, it is reasonable to provide them with the option to delete data from the application itself. Localstorage provides a clear () method to achieve this purpose. The following code is triggered when you click a reset button in your application. If you want to remove a specific entry from the bucket, you can use the removeitem () method to delete a single key from the local bucket.

function onReset(){
if(checkLocalStorageSupport())
{
window.localStorage.clear();
}}
Handle changes

The Web storage API also contains a method for listening to and responding to any changes to the local storage. By adding an event listener and listening for a storage event, the application can respond to the localstorage change. The data in the event contains the name, new value, old value (if any) of the changed key, and the URL of the page that calls the API. You can use the following method to implement the localstorage API specification, that is, the session that initiates the event will not be able to see the event trigger. This is because the specification requires that the event be triggered only for others, rather than for changing the stored tag or session.

To listen to stored events, you must first add an event listener:

window.addEventListener("storage",onStorageChange); 

Create an onstoragechange event to handle storage events.

function onStorageChange(e) {
if(e.key =="name")
{
alert(e.newValue +' just added their name to local storage');
} }

In addition, there is a similar API for Data creation, which is only valid for individual sessions. By using the sessionstorage object instead of the localstorage object, any stored data is automatically cleared when the user leaves the page. In fact, the API has exactly the same method, so you can check carefully and use sessionstorage to replace localstorage, and then local data will be saved until users close their browsers or labels that contain applications.

Offline storage

Sometimes, only some data is stored on the user's machine. In many cases, the entire application must run offline, not just to store some data. In this case, HTML5 includes the ability to cache files and resources on users' machines at high speed, so that browsers can access them without internet connection. This means that a large amount of data, such as images, JavaScript files, HTML files, and CSS files that constitute web applications, can be stored locally, and even accessed without Internet connections. The key to this function is to create a high-speed cache manifest file.

Use the manifest File

The manifest file is an integral part of the new manifest attribute of the root HTML tag of the page. It is a file on a Web server that lists all the files that the browser should download and save for future use. It has. the manifest extension and its only major gotcha are required by the corresponding web server. the manifest MIME type. Therefore, make sure that the web server that resides in the application is correctly provided. manifest file. The manifest file has a basic architecture. Each manifest file starts with cache manifest and starts from here to list all files that require high-speed caching by browsers for offline access. Below is a simple example, which can store some JavaScript, a CSS file, some images and corresponding HTML pages:

CACHE MANIFESTstyle.cssofflinescript.jsimages/dreamweaver_logo.pngimages/edge_logo.png

The corresponding path is related to the HTML page that the user is accessing. When creating a high-speed cache manifest file, you must understand some other options. One option is that files cannot be cached at high speed. Maybe only dynamic scripts or some content that can be obtained online are meaningful. The cache manifest file can be divided into sections that tell the browser how to respond to certain content ). By creating a network and listing files that cannot be cached at high speed, the browser can ignore these files and never obtain them offline.

Another scenario is when users attempt to access a page without high-speed cache or some content that should be cached but not properly saved. The high-speed cache manifest API provides a fallback section that points to a page loaded in the preceding example. Therefore, when users try to access some unsaved content, they will see a message about offline prompts. The following is a theoretical structure of the high-speed cache manifest file that contains these sections:

CACHE MANIFESTNETWORK:my_dynamic_script.cgiFALLBACK:my_offline_message.htmlCACHE:style.cssofflinescript.jsimages/dreamweaver_logo.pngimages/edge_logo.png

In this example, I provide an HTML page with an external JavaScript page and an external CSS page. The HTML page displays text describing an Adobe logo. When you click an image, JavaScript will replace the image and text for the other logo. Below is the corresponding HTML code, followed by the JavaScript function:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Adobe Logos</title>

<script src="offlinescript.js"></script>
<link href="style.css" rel="stylesheet"/>
<body>
<div id="textContent">This is the Edge logo:</div><br />


<p class="small">Click on the logo to swap it out.</p>
</body>

// JavaScript Document
function onLogoClick(e)
{
var currentContent =
window.document.getElementById("textContent").innerHTML;
if(currentContent =="This is the Edge logo:")
{
window.document.getElementById("textContent").innerHTML =
"This is the Dreamweaver logo:";
window.document.logo.src =
"images/dreamweaver_logo.png";
} else {
window.document.getElementById("textContent").innerHTML =
"This is the Edge logo:";
window.document.logo.src ="images/edge_logo.png";
}

}

The key part of all this code is the HTML tag with the manifest attribute. It points to my cache. manifest file referenced above. This manifest file can instruct the browser to download all the files in the list. Regardless of whether you download these files, the corresponding browser automatically downloads all files contained in the manifest file. This means that both images will be saved for offline access, even if the second image is not loaded to the page until I interact with the corresponding content. Therefore, you only need to load the page once, so that I can fully interact with it offline, and the two images will rotate.

Understand events

The last part of offline access that needs to be mentioned, but is very important, is the events that occur in the cache process. When the browser encounters the manifest attribute, it will trigger a series of events in the window. applicationcache object. The first event is to trigger a checking event. This event determines the operations that need to be performed using this special high-speed cache file. Google Chrome developers can comprehensively check events when saving data in the cache area (see figure 1 ).

Figure 1.Events that occur when data is saved in the cache

If this is the first time a user accesses this website, a download event is triggered and the corresponding web browser will carefully check and download all resources contained in the manifest file. It can read the corresponding manifest file, determine how many files it needs to download, and update the status of each file in the form of a progress event. The progress event contains a loaded variable and a total variable, so that developers can determine how much content has been stored in the cache.

function onProgress(e)
{
var content = window.document.getElementById("loadedInfo").innerHTML;
window.document.getElementById("loadedInfo").innerHTML = content +'
Loaded file '+ e.loaded +' of '+ e.total;
}

When all files are saved, the browser will trigger a cached event to notify developers that all files used offline are successfully saved.

The browser will check whether the content in the manifest file has changed at any time when the user accesses the page. If not, it triggers a noupdate event and continues running. If any content changes, it will go through the same process as above; it will trigger a downloading event containing a series of progress events until all the corresponding files are updated. When this event occurs, instead of triggering a cached event, the browser triggers an updateready event, indicating that all files have been updated and can be used offline.

The last worrying event is the error event, which will be triggered when an application fails. These faults may occur when files cannot be correctly loaded, browsers cannot access the cache manifest file, or one or more files listed by manifest do not exist. To capture these faults, you only need to add an event listener for the error event.

window.applicationCache.addEventListener("error",onError);

function onError(e)
{
window.document.getElementById("loadedInfo").innerHTML ="Something went wrong while saving the files for offline use.";
} 
Database storage

The last storage type introduced by html5. Initially there was a web SQL specification *, but it is no longer in use now. Now, most people have moved to the indexed database API *, and it seems that this will be the way out to store information in relational databases. Firefox and chrome both support indexeddb, but because the corresponding specifications and support functions are constantly changing, it is beyond the scope of this article. In the future, when this status changes, I will update it accordingly.

Next reading

In this article, I have explored two main methods to store information locally. The first method provides some basic data storage technologies in the form of web storage APIs. By using this method, you can save name value pairs (name value pair) outside a session or for a single session ). The second method is the application cache manifest, which allows developers to save all files on their local machines so that they can be accessed offline.

For more information about the HTML5 storage API, see the following resources:

  • The past, present, and future of local storage for Web applications (the past, present, and future of local storage for Web applications )*
  • HTML5 rocks: Local Storage (HTML5 rocks: Local Storage )*
  • Dr Dobbs: HTML5 web storage (Dr Dobbs: HTML5 web storage )*
  • Document: W3C draft: Web storage (Documentation: W3C draft: Web storage )*
Tags: HTML5 storage API

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.