Home Web Front-end JS Tutorial JavaScript uses localStorage to store data

JavaScript uses localStorage to store data

Aug 05, 2022 am 11:54 AM
javascript

This article brings you relevant knowledge about javascript, which mainly introduces JavaScript's use of localStorage to store data. The sample code in the article is introduced in great detail and has certain reference value. I hope it will be useful to everyone. helpful.

JavaScript uses localStorage to store data

[Related recommendations: javascript video tutorial, web front-end

Background

In the past, js used Session and Cookie to store information, as if I was still stuck at that time, When I asked my colleagues if they had any new solutions, I learned that there is already HTML5 localStorage local storage, which can store data on the browser side.

I remember the earliest Cookies could only store very small things, about 4KB, and the security was very poor. In the IE6 era, a domain name could only hold 20 cookies. Cookies, the restrictions are quite large. Of course, IE also has userData, which is of no use. Flash also comes with a Storage, which is relatively large and has about 25 times the space of Cookie. At that time, Flash was also abandoned now.

In the H5 era, it will be unified, LocalStorage will dominate the world. The official recommendation is that each website is 5MB , which is very large. Although browser settings will vary, it is generally enough to store some JSON or strings or cache.

HTML5 LocalStorage local storage

  • sessionStorage: The saved data is used for a session of the browser, When the session ends (usually the window is closed), the data is cleared;
  • #localStorage: The saved data exists for a long time and will be used the next time you visit the website. At this time, the web page can directly read the previously saved data. Except for the different storage periods, the properties and methods of the two objects are exactly the same.

They are very much like an enhanced version of the cookie mechanism, although they can use much larger storage space. However, like cookies, they are also subject to same domain restrictions. The data stored in a web page can only be read by web pages in the same domain.

By checking whether the window object contains sessionStorage and localStorage attributes, you can determine whether the browser supports these two objects.

function checkStorageSupport()
{
 // sessionStorage
 if (window.sessionStorage) {
  return true;
 } else {
  return false;
 }
 
 // localStorage
 if (window.localStorage) {
  return true;
 } else {
  return false;
 }
}
Copy after login

Storage operation

The data saved by sessionStorage and localStorage are all represented by "Key-Value key-value pairs" form exists. In other words, each item of data has a key name and a corresponding value. All data are saved in text format.

//sessionStorage 操作
sessionStorage.setItem("key","value");     // setItem方法,存储变量名为key,值为value的变量
var valueSession = sessionStorage.getItem("key");  // getItem方法,读取存储变量名为key的值
sessionStorage.removeItem('key');      // removeItem方法,删除变量名为key的存储变量
sessionStorage.clear();        // clear方法,清除所有保存数据
//localStorage 操作
localStorage.setItem("key","value");     // 存储变量名为key,值为value的变量
localStorage.key = "value"        // 同setItem方法,存储数据
var valueLocal = localStorage.getItem("key");   // 读取存储变量名为key的值
var valueLocal = localStorage.key;      // 同getItem,读取数据
localStorage.removeItem('key');      // removeItem方法,删除变量名为key的存储变量
localStorage.clear();         // clear方法,清除所有保存的数据

// 利用length属性和key方法,遍历所有的数据
for(var i = 0; i < localStorage.length; i++)
{
 console.log(localStorage.key(i));
}

// 存储 localStorage 数据为 Json 格式
value = JSON.stringify(jsonValue);      // 将 JSON 对象 jsonValue 转化成字符串
localStorage.setItem("key", value);     // 用 localStorage 保存转化好的的字符串

// 读取 localStorage 中 Json 格式数据
var value = localStorage.getItem("key");    // 取回 value 变量
jsonValue = JSON.parse(value);      // 把字符串转换成 JSON 对象
Copy after login

Storage event

When the stored data changes, the storage event will be triggered. We can specify a callback function for this event.

window.addEventListener("storage",onStorageChange);
Copy after login

The callback function accepts an event object as a parameter. The key attribute of this event object saves the changed key name.

function onStorageChange(e)
{
  console.log(e.key); 
}
Copy after login

In addition to the key attribute, the event object has three attributes:

  • oldValue: the value before update. If the key is newly added, this attribute is null.
  • newValue: updated value. If the key was deleted, this property is null.
  • url: The URL of the web page that originally triggered the storage event.

Special note is that this event is not triggered on the current page that causes data changes. If the browser opens multiple pages under a domain name at the same time, when one of the pages changes the data of sessionStorage or localStorage, the storage events of all other pages will be triggered, and the storage event will not be triggered by the original page. Through this mechanism, communication between multiple windows can be achieved. Among all browsers, except IE, it will trigger the storage event on all pages.

Extended knowledge

1. localStorage and sessionStorage are two storage methods provided by HTML5 web storage. They are available in IE7 and above and most browsers. All servers support

2. The difference between localStorage and sessionStorage:

(1) LocalStorage and sessionStorage are both objects used to store temporary information on the client.

(2). They can only store objects of string type (although other native types of objects can be stored in the specification, but so far no browser has implemented it).

(3). The localStorage life cycle is permanent, which means that unless the user clears localStorage information on the UI provided by the browser, this information will exist forever. (recorded in memory)

The sessionStorage life cycle is the current window or tab. Once the window or tab is closed, all data stored through sessionStorage will be cleared (session storage)

(4), Different browsers cannot share information in localStorage or sessionStorage. Different pages in the same browser can share the same localStorage (the pages belong to the same domain name and port), but sessionStorage information cannot be shared between different pages or tabs.

It should be noted here that pages and tabs only refer to top-level windows. If a tab page contains multiple iframe tags and they belong to the same source page, then sessionStorage can be shared between them. (Same origin principle)

3. The size of data that can be stored by localStorage and sessionStorage is generally 5MB

[Related recommendations: javascript video tutorial, web front-end

The above is the detailed content of JavaScript uses localStorage to store data. 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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles