search
HomeWeb Front-endH5 TutorialIntroduction to WebStorage for HTML5 local storage

Introduction to WebStorage for HTML5 local storage

Nov 13, 2020 pm 05:52 PM
html5local storage

Introduction to WebStorage for HTML5 local storage

WebStorage is one of the local storage solutions in HTML5. Before the introduction of the WebStorage concept of HTML5, IE User Data, Flash Cookies, Google Gears, etc. were removed and the names were unreliable solutions. scheme, the browser-compatible local storage scheme only uses cookies. Some students may ask, since we have cookie local storage, why do we need to introduce the concept of WebStorage?

The flaws of cookie are very obvious

1. Data size: As a storage container, the size of cookie is limited to about 4KB, which is very cheating. , especially for today’s complex business logic requirements, the 4KB capacity not only stores some configuration fields but also simple single-value information. For most developers, they really don’t know what to expect.

2. Security issues: Since the cookie in the HTTP request is passed in clear text (HTTPS is not), the security issues are still huge.

3. Network burden: We know that cookies will be attached to each HTTP request and will be transmitted in the headers of HttpRequest and HttpResponse, so some unnecessary traffic losses will be added.

WebStorage

WebStorage is one of the new local storage solutions for HTML, but it is not a standard developed to replace cookies. Cookies are used as part of the HTTP protocol to handle clients and servers. Communication is indispensable, and session relies on the implementation of client state retention. The purpose of WebStorage is to solve the problem of local storage that should not be done with cookies, but has to use cookies.

WebStorage provides two types of APIs: localStorage and sessionStorage. The difference between the two can be roughly understood by looking at the names. LocalStorage stores data locally permanently unless it is explicitly deleted or cleared. The data stored in sessionStorage It is only valid during the session and is automatically deleted when the browser is closed. Both objects have a common API

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();
};
  • length: the only attribute, read-only, used to obtain the number of key-value pairs in the storage.
  • key: Get the key name of the storage based on the index
  • getItem: Get the corresponding value in the storage based on the key
  • setItem: Add a key-value pair to the storage
  • removeItem: Delete the key-value pair according to the key name
  • clear: Clear the storage object

Use

In a browser that implements WebStorage, the page has Two global objects localStorage and sessionStorage

Introduction to WebStorage for HTML5 local storage

Taking localStorage as an example, look at a simple operation code

var ls=localStorage;
            console.log(ls.length);//0
            ls.setItem('name','Byron');
            ls.setItem('age','24');
            console.log(ls.length);//2
            
            //遍历localStorage
            for(var i=0;i<ls.length><h3 id="Event">Event</h3>
<p>At the same time HTML5 A storage event is specified, which is triggered when WebStorage changes. You can use this to monitor storage modifications on different pages. </p>
<pre class="brush:php;toolbar:false">interface StorageEvent : Event {
  readonly attribute DOMString key;
  readonly attribute DOMString? oldValue;
  readonly attribute DOMString? newValue;
  readonly attribute DOMString url;
  readonly attribute Storage? storageArea;
};
  • key: the key of the key-value pair
  • oldValue: modification Previous value
  • newValue: modified value
  • url: page url that triggered the change
  • StorageArea: changed Storage

Definition in index.php

<a>Test</a>
window.addEventListener('storage',function(e){
                console.log(e.key+' is changed form '+e.oldValue+' to '+e.newValue+' by '+e.url );
                console.log(e.storageArea ==localStorage);
            },false);
            
            localStorage.setItem('userName','Byron');

test.php

localStorage.setItem('userName','Casper');

You can see the index when you click the link on the index.php page to access test.php .php console output log:

userName is changed form Byron to Casper by http://localhost/test.php

true

1. In terms of capacity, WebStorage generally provides 5M of storage space in browsers, which is not enough to store videos and pictures, but it is enough for most operations.

2. In terms of security WebStorage is not sent as an HTTP header by the browser, so it is relatively safe

3. In terms of traffic, because WebStorage is not transmitted to the server, unnecessary traffic can be saved, so that for high-frequency visits or targeted The web pages for mobile devices are still very good.

This does not mean that WebStorage can replace cookies, but that with WebStorage, cookies can only do what they should do - serve as a channel for client-server interaction and maintain client state. So WebStorage is superior to cookies just as a local storage solution.

Notes

1. Browser compatibility, this is almost the easiest to implement among all new HTML5 features, because it is supported by IE8 browsers and can be used in IE7 and IE6 IE User Data implementation.

Introduction to WebStorage for HTML5 local storage

2. Since localStorage and sessionStorage are both objects, we can also obtain and modify key-value pairs through ".key" or "[key]". , but this is not recommended

localStorage.userName='Frank';
console.log(localStorage['userName']);

3. Although localStorage is stored locally, different browsers store data independently, so localStorage stored on Chrome cannot be obtained on FireFox.

4. localStorage and sessionStorage can only store string types. For complex objects, you can use the stringify and parse of the JSON object provided by ECMAScript to handle them. For lower versions of IE, you can use json2.js

5. In addition to the console, Chrome also provides a very intuitive display method for local storage, which is very convenient when debugging.

Introduction to WebStorage for HTML5 local storage

For more programming-related knowledge, please visit : Programming learning website! !

The above is the detailed content of Introduction to WebStorage for HTML5 local storage. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor