当前位置:网站首页>Browser local storage
Browser local storage
2022-07-01 07:19:00 【18 hate programming】
List of articles
Scene Introduction
First, we can understand what is the local storage of browsers through a scenario
For example, we open Taobao Search psp( Without logging in to your account ), Then close the website , We reopen Taobao , It can be found in the search history psp.
Why is it like this ? Here is the local storage of the website with the help of the browser , The data is stored on the hard disk of the computer .
We can use the developer tools of the browser to view :
Similarly, we can store things in the browser !
Browser local storage
Web Storage API Provides sessionStorage ( Session storage )
and localStorage( The local store )
Two storage objects are used to add the data of the web page 、 Delete 、 modify 、 Query operation .
- localStorage For long-term preservation of data across the site , Saved data has no expiration time , Until removed by hand .( If you close the browser, it won't disappear )
- sessionStorage Used to temporarily save the same window ( Or tabs ) The data of , The data will be deleted after closing the window or tab .
localStorage There are only two ways to delete data :
① Programmers use related cleanup methods
② The user manually deletes the cached data of the browser
Corresponding API And attributes :
window.localStorage
grammar :
window.localStorage
Save data syntax :
localStorage.setItem("key", "value");
Key value pairs will eventually be stored as strings
Read data syntax :
var lastname = localStorage.getItem("key");
Delete data syntax :
localStorage.removeItem("key");
Clear data syntax :
localStorage.clear();
We now create a web page and save some data on it for a long time :
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button onclick="storeData()"> Click on me to store data on the web page </button>
</body>
<script> function storeData() {
localStorage.setItem(' Zhang San ','18') } </script>
</html>
If we want to store an object :
<body>
<button onclick="storeData()"> Click on me to store data on the web page </button>
</body>
<script> let person = {
name:'Tom',age:'20'} function storeData() {
localStorage.setItem(' Zhang San ',6666) localStorage.setItem('msg',JSON.stringify(person)) } </script>
Here are some api Use it all :
<body>
<button onclick="storeData()"> Click on me to store data on the web page </button>
<button onclick="watchData()"> Click on my data on the web page </button>
<button onclick="deleteData()"> Click on me to delete data on the web page </button>
<button onclick="clearData()"> Click on me to clear the data on the web page </button>
</body>
<script> let person = {
name:'Tom',age:'20'} function storeData() {
localStorage.setItem(' Zhang San ',6666) localStorage.setItem('msg',JSON.stringify(person)) } function watchData() {
console.log(localStorage.getItem(' Zhang San ')) console.log(JSON.parse(localStorage.getItem('msg'))) } function deleteData() {
localStorage.removeItem(' Zhang San ') } function clearData() {
localStorage.clear() } </script>
Objects will be displayed as strings if viewed directly , Obviously this is not what we want , We can use JSON.parse Analyze , We can get the object we want again .
If you view non-existent data , Will be displayed null.
JSON.parse(null) The result is still null
window.sessionStorage
And window.localStorage The method of use is exactly the same
Difference is that :sessionStorage Used to temporarily save the same window ( Or tabs ) The data of , The data will be deleted after closing the window or tab .
summary
webStorage
The storage content size generally supports 5MB about ( Different browsers may be different )
Browser side through Window.sessionStorage and Window.localStorage Property to implement the local storage mechanism .
relevant API:
xxxxxStorage.setItem('key', 'value');
This method takes a key and a value as arguments , Key value pairs are added to the store , If key name exists , Then update its corresponding value .xxxxxStorage.getItem('person');
This method takes a key name as an argument , Return the value corresponding to the key name .
xxxxxStorage.removeItem('key');
This method takes a key name as an argument , And remove the key name from the storage .
xxxxxStorage.clear()
This method will empty all data in the storage .
remarks :
- SessionStorage The stored content will disappear as the browser window closes .
- LocalStorage Stored content , It needs to be cleared manually to disappear .
xxxxxStorage.getItem(xxx)
If xxx Corresponding value Can't get , that getItem The return value of null.JSON.parse(null)
The result is still null.
边栏推荐
- 【剑指offer&牛客101】中那些高频笔试,面试题——链表篇
- 电脑有网络,但所有浏览器网页都打不开,是怎么回事?
- 【图像处理】图像直方图均衡化系统含GUI界面
- 【深圳IO】精确食品称(汇编语言的一些理解)
- Automated test platform (13): interface automation framework and platform comparison, application scenario analysis and design ideas sharing
- Chinese explanation of common rclone subcommands
- 华泰证券开户是安全可靠的么?怎么开华泰证券账户
- ctfshow-web351(SSRF)
- 在券商账户上买基金安全吗
- Rclone Chinese document: a collection of common commands
猜你喜欢
Will Internet talents be scarce in the future? Which technology directions are popular?
【编程强训2】排序子序列+倒置字符串
Alibaba OSS postman invalid according to policy: policy condition failed: ["starts with", "key", "test/"]
Product learning (III) - demand list
熱烈祝賀五行和合酒成功掛牌
Image style migration cyclegan principle
灰度何以跌下神坛?
图像风格迁移 CycleGAN原理
C language implementation [Sanzi chess game] (step analysis and implementation source code)
女生适合学产品经理吗?有什么优势?
随机推荐
DC-4 target
【Tikhonov】基于Tikhonov正则化的图像超分辨率重建
【LINGO】求解二次规划
如何画产品架构图?
Open source! Wenxin large model Ernie tiny lightweight technology, accurate and fast, full effect
Challenges faced by operation and maintenance? Intelligent operation and maintenance management system to help you
[classification model] Q-type cluster analysis
解决kaniko push镜像到harbor时报错(代理导致):unexpected status code 503 Service Unavailable
We found a huge hole in MySQL: do not judge the number of rows affected by update!!!
iNFTnews | 从《雪崩》到百度“希壤”,元宇宙30年的16件大事
用手机在指南针上开户靠谱吗?这样有没有什么安全隐患
【LINGO】求无向图的最短路问题
C # read and write customized config file
8 figures | analyze Eureka's first synchronization registry
Is it suitable for girls to study product manager? What are the advantages?
[programming training 2] sorting subsequence + inverted string
[the path of system analysts] Chapter 5: software engineering of double disk (reverse clean room and Model Driven Development)
ctfshow-web355,356(SSRF)
Reply and explanation on issues related to "online training of network security education in 2022"
Why are so many people turning to product managers? What is the development prospect of product manager?