Home Web Front-end H5 Tutorial How to use Web Storage

How to use Web Storage

Jun 04, 2018 am 11:31 AM
storage web storage

This time I will show you how to use Web Storage storage, and what are the precautions for using Web Storage storage. The following is a practical case, let's take a look.

localStorage-------sessionStorage

Web Storage features:

1. Key- -Simple storage form of Value type

2. It can be read and written in the same form as other ordinary javascript objects

3. Large capacity-->5M (compared to cookie)--(cookie is only 4KB and will be brought along when sending a request, which affects the speed)

4. It can only be accessed when it comes from the same source.

The following uses localStorage as an example----》sessionStorage and localStorage are basically the same, but sessionStorage is based on sessions. Disappears when the window is closed. However, localStorage is data stored locally. Unless deleted through a program or manually, the data will not be lost.

Similar to ordinary JavaScript objects, you can use dot (.) operations and [ ] bracket operations to access properties.

For example: localStorage.setItem("foo","1") \ localStorage.foo="1" \ localStorage["foo"]="1"

Commonly used APIs: setItem(), getItem(), clear().

When the object is stored, when reading and writing, the object needs to be converted into JSONString for storage, and two functions JSON.stringify( are introduced) obj), JSON.parse(str)

For example: var obj={x:1,y:2} Storage: localStorage.obj=JSON.stringify(obj), read :var obj2=localStorage.parse(localStorage.obj).

Data enumeration: 1. Traversal through key method and length attribute 2. for in traversal

1: for (var i= 0;i

2: for (var key in localStorage){ if(localStorage.hasOwnProperty(key)){var value=localStorage[key]; console.log(key ":" value);} }

storage event

After a certain window changes the web Storage data, the storage event is triggered in all windows except the window where the data is changed.

window.addEventListener('storage',function(event){ console.log(event.key) }.false);

The following lists several commonly used attributes of event event objects.

key (updated key name), oldValue (value before update), newValue (value after update), url (url of the updated page)

Management of namespace----Since localStorage data will automatically disappear if it is incorrect, if too many attributes are added indiscriminately, subsequent management will become very difficult. We can manage it through namespaces.

	var serviceName="SERVICENAME",storage=null;
	//通过load事件读取数据至本地变量
	window.onload=function(){
		try{
			storage=JSON.parse(localStorage[serviceName] || '{}');
		}catch{
			storage={};
		}
	}
	//通过onbeforeunload时间将数据写入localStorage
	window.onbeforeunload=function(){
		localStorage[serviceName]=JSON.stringify(storage)
	}

1. Write the data of localStorage to the local variable storage, then the access speed will be faster than the access speed of localStroage.

2. Different pages or modules are named with different serviceNames to avoid attribute name conflicts.

3. Since a page only reads and writes localStorage once, so the storage event cannot be triggered on the page. So when necessary, we need to encapsulate methods to update localStorage data or synchronize data from other tabs.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How to use source css3 to implement the ring loading progress bar

How to access the object properties and methods of JS

The above is the detailed content of How to use Web Storage. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Huawei will launch innovative MED storage products next year: rack capacity exceeds 10 PB and power consumption is less than 2 kW Huawei will launch innovative MED storage products next year: rack capacity exceeds 10 PB and power consumption is less than 2 kW Mar 07, 2024 pm 10:43 PM

This website reported on March 7 that Dr. Zhou Yuefeng, President of Huawei's Data Storage Product Line, recently attended the MWC2024 conference and specifically demonstrated the new generation OceanStorArctic magnetoelectric storage solution designed for warm data (WarmData) and cold data (ColdData). Zhou Yuefeng, President of Huawei's data storage product line, released a series of innovative solutions. Image source: Huawei's official press release attached to this site is as follows: The cost of this solution is 20% lower than that of magnetic tape, and its power consumption is 90% lower than that of hard disks. According to foreign technology media blocksandfiles, a Huawei spokesperson also revealed information about the magnetoelectric storage solution: Huawei's magnetoelectronic disk (MED) is a major innovation in magnetic storage media. First generation ME

Vue3+TS+Vite development skills: how to encrypt and store data Vue3+TS+Vite development skills: how to encrypt and store data Sep 10, 2023 pm 04:51 PM

Vue3+TS+Vite development tips: How to encrypt and store data. With the rapid development of Internet technology, data security and privacy protection are becoming more and more important. In the Vue3+TS+Vite development environment, how to encrypt and store data is a problem that every developer needs to face. This article will introduce some common data encryption and storage techniques to help developers improve application security and user experience. 1. Data Encryption Front-end Data Encryption Front-end encryption is an important part of protecting data security. Commonly used

Git installation process on Ubuntu Git installation process on Ubuntu Mar 20, 2024 pm 04:51 PM

Git is a fast, reliable, and adaptable distributed version control system. It is designed to support distributed, non-linear workflows, making it ideal for software development teams of all sizes. Each Git working directory is an independent repository with a complete history of all changes and the ability to track versions even without network access or a central server. GitHub is a Git repository hosted on the cloud that provides all the features of distributed revision control. GitHub is a Git repository hosted on the cloud. Unlike Git which is a CLI tool, GitHub has a web-based graphical user interface. It is used for version control, which involves collaborating with other developers and tracking changes to scripts and

What are web standards? What are web standards? Oct 18, 2023 pm 05:24 PM

Web standards are a set of specifications and guidelines developed by W3C and other related organizations. It includes standardization of HTML, CSS, JavaScript, DOM, Web accessibility and performance optimization. By following these standards, the compatibility of pages can be improved. , accessibility, maintainability and performance. The goal of web standards is to enable web content to be displayed and interacted consistently on different platforms, browsers and devices, providing better user experience and development efficiency.

How to enable administrative access from the cockpit web UI How to enable administrative access from the cockpit web UI Mar 20, 2024 pm 06:56 PM

Cockpit is a web-based graphical interface for Linux servers. It is mainly intended to make managing Linux servers easier for new/expert users. In this article, we will discuss Cockpit access modes and how to switch administrative access to Cockpit from CockpitWebUI. Content Topics: Cockpit Entry Modes Finding the Current Cockpit Access Mode Enable Administrative Access for Cockpit from CockpitWebUI Disabling Administrative Access for Cockpit from CockpitWebUI Conclusion Cockpit Entry Modes The cockpit has two access modes: Restricted Access: This is the default for the cockpit access mode. In this access mode you cannot access the web user from the cockpit

How do PHP and swoole achieve efficient data caching and storage? How do PHP and swoole achieve efficient data caching and storage? Jul 23, 2023 pm 04:03 PM

How do PHP and swoole achieve efficient data caching and storage? Overview: In web application development, data caching and storage are a very important part. PHP and swoole provide an efficient method to cache and store data. This article will introduce how to use PHP and swoole to achieve efficient data caching and storage, and give corresponding code examples. 1. Introduction to swoole: swoole is a high-performance asynchronous network communication engine developed for PHP language. It can

How to correctly use sessionStorage to protect sensitive data How to correctly use sessionStorage to protect sensitive data Jan 13, 2024 am 11:54 AM

How to correctly use sessionStorage to store sensitive information requires specific code examples. Whether in web development or mobile application development, we often need to store and process sensitive information, such as user login credentials, ID numbers, etc. In front-end development, using sessionStorage is a common storage solution. However, since sessionStorage is browser-based storage, some security issues need to be paid attention to to ensure that the stored sensitive information is not maliciously accessed and used.

what does web mean what does web mean Jan 09, 2024 pm 04:50 PM

The web is a global wide area network, also known as the World Wide Web, which is an application form of the Internet. The Web is an information system based on hypertext and hypermedia, which allows users to browse and obtain information by jumping between different web pages through hyperlinks. The basis of the Web is the Internet, which uses unified and standardized protocols and languages ​​to enable data exchange and information sharing between different computers.

See all articles