search
HomeWeb Front-endH5 TutorialHTML5 Advanced Tutorial - Web Storage

Preface

HTML5 There are two web Storage storage methods: localStorage and sessionStorage.

Both methods save data through key-value pairs, which are easy to access and do not affect website performance. Their usage is the same, but their storage times are different.
LocalStorage data is saved on local hardware and can be saved permanently. The api can be manually called to clear the data. sessionStorage is stored in the session object and will be cleared when the browser is closed.

The size of web Storage is limited on the browser. The size of different browsers will be different. In mainstream browsers, the size is about 5M, which is actually enough to store ordinary data.

Usage

Take localStorage as an example, the usage of sessionStorage is the same:

setItem

Save data: localStorage.setItem(key,value);

Example:

localStorage.setItem('name','Hello World');

When the keys are the same, the previous value will be overwritten to modify the data. If value is an object, it needs to be converted to a json string, otherwise what you read will be [object Object]

getItem

Read data: localStorage.getItem(key);

Example:

localStorage.getItem('name');       // Hello World

removeItem

Remove Single data: localStorage.removeItem(key);

Example:

localStorage.removeItem('name');
localStorage.getItem('name');       // null

After deleting the data with key name, if the data cannot be obtained in loaclStorage, null will be returned;

clear

Delete all data: localStorage.clear ();

Example:

localStorage.clear();

All data in localStorage will be deleted at this time.

key

Get the key of a index: localStorage.key(index);
Example:

localStorage.setItem('name1','Hello World');
localStorage.setItem('name2','Hello Linxin');
localStorage.key(1);                // name2

Get the index as 1 The key is name2.

Constructor

In actual projects, localStorage may need to be operated multiple times. We can operate it better through a constructor.

Example:

var localEvent = function (item) {
    this.get = function () {
        return localStorage.getItem(item);
    }
    this.set = function (val) {
        localStorage.setItem(item, val);
    }
    this.remove = function () {
        localStorage.removeItem(item);
    }
    this.clear = function () {
        localStorage.clear();
    }
}

// 使用new字符把构造函数实例化出多个对象
var local1 = new localEvent('name1');
var local2 = new localEvent('name2');

local1.set('Hello World');
local2.set('Hello Linxin');

local1.get();               // Hello World
local2.get();               // Hello Linxin

This is just a simple demonstration. If we usually store objects in our projects, we need to do some processing in the code.

Listen to storage Events

You can listen to the storage event of the window object and specify its Event processing function, when localStorage or sessionStorage is processed in the page When modified, the corresponding processing function will be triggered.

window.addEventListener('storage',function(e){
    console.log('key='+e.key+',oldValue='+e.oldValue+',newValue='+e.newValue);
})

The time object (e parameter value) that triggers the event has several attributes:

  • key: key value.

  • oldValue: The value before modification.

  • newValue: The modified value.

  • url: Page url.

  • storageArea: The modified storage object.

Note: In Google Chrome, the storage needs to be modified in different tabs to trigger this event, that is, web page A listens to this event, and localStorage is modified in web page B, then the web page A will trigger the event function. But in IE, modifying localStorage on the same web page will trigger this event.

Debugging

Google Chrome’s own debugging tools (chrome devtools) are very easy to use and can be used to debug localStorage and sessionStorage. Open the browser and press f12 to bring up the debugging tool. You can see Application. Click to open and you can see Storage in the left column, including localStorage, sessionStorage, IndexedDB, etc. Select the domain name of the website we want to debug, and you can see the corresponding key on the right. and value, which can be edited or deleted by right-clicking.

Compatible

It is compatible with IE8 and above, but it is special and only supports it when it needs to be opened on the server. Directly double-clicking file:// to open the file is incompatible.

Only IE11 supports opening under file://. Other browsers have a high degree of support, including compatibility on mobile phones.

【Related recommendations】

1. Free h5 online video tutorial

2. HTML5 full version manual

3. php.cn original html5 video tutorial

The above is the detailed content of HTML5 Advanced Tutorial - Web Storage. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5: Tools, Frameworks, and Best PracticesH5: Tools, Frameworks, and Best PracticesApr 11, 2025 am 12:11 AM

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

The Legacy of HTML5: Understanding H5 in the PresentThe Legacy of HTML5: Understanding H5 in the PresentApr 10, 2025 am 09:28 AM

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 Code: Accessibility and Semantic HTMLH5 Code: Accessibility and Semantic HTMLApr 09, 2025 am 12:05 AM

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.

Is h5 same as HTML5?Is h5 same as HTML5?Apr 08, 2025 am 12:16 AM

"h5" and "HTML5" are the same in most cases, but they may have different meanings in certain specific scenarios. 1. "HTML5" is a W3C-defined standard that contains new tags and APIs. 2. "h5" is usually the abbreviation of HTML5, but in mobile development, it may refer to a framework based on HTML5. Understanding these differences helps to use these terms accurately in your project.

What is the function of H5?What is the function of H5?Apr 07, 2025 am 12:10 AM

H5, or HTML5, is the fifth version of HTML. It provides developers with a stronger tool set, making it easier to create complex web applications. The core functions of H5 include: 1) elements that allow drawing graphics and animations on web pages; 2) semantic tags such as, etc. to make the web page structure clear and conducive to SEO optimization; 3) new APIs such as GeolocationAPI support location-based services; 4) Cross-browser compatibility needs to be ensured through compatibility testing and Polyfill library.

How to do h5 linkHow to do h5 linkApr 06, 2025 pm 12:39 PM

How to create an H5 link? Determine the link target: Get the URL of the H5 page or application. Create HTML anchors: Use the <a> tag to create an anchor and specify the link target URL. Set link properties (optional): Set target, title, and onclick properties as needed. Add to webpage: Add HTML anchor code to the webpage where you want the link to appear.

How to solve the h5 compatibility problemHow to solve the h5 compatibility problemApr 06, 2025 pm 12:36 PM

Solutions to H5 compatibility issues include: using responsive design that allows web pages to adjust layouts according to screen size. Use cross-browser testing tools to test compatibility before release. Use Polyfill to provide support for new APIs for older browsers. Follow web standards and use effective code and best practices. Use CSS preprocessors to simplify CSS code and improve readability. Optimize images, reduce web page size and speed up loading. Enable HTTPS to ensure the security of the website.

How to generate links with h5How to generate links with h5Apr 06, 2025 pm 12:33 PM

h5 pages can generate links in two ways: create links manually or use short link services. By manually creating, you just need to copy the URL of the h5 page; through the short link service, you need to paste the URL into the service and then get the shortened URL.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment