当前位置:网站首页>JS client storage
JS client storage
2022-06-27 10:17:00 【Xiaaoke】
List of articles
Cookie
HTTP Cookie( Also called Web Cookie Or browser Cookie) Is a small piece of data that the server sends to the user's browser and stores locally , It is carried and sent to the server the next time the browser makes a request to the same server . Usually , It is used to tell the server whether two requests are from the same browser , Such as maintaining the login status of the user .Cookie To base on No state Of HTTP It is possible for protocols to record stable state information .
Cookie Mainly used in the following three aspects :
- Session state management ( Such as user login status 、 The shopping cart 、 Game score or other information to be recorded )
- Personalization ( Such as user-defined settings 、 Theme, etc )
- Browser behavior tracking ( Such as tracking and analyzing user behavior )
Native use
// Create a name name, The corresponding value is value Of cookie, Because no expiration time is set , The default expiration time is when the website is closed
document.cookie="name=cookie";
// You can also for cookie Add an expiration time ( With UTC or GMT Time ). By default ,cookie Delete... When browser is closed :
document.cookie="username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT";
// You can use path Parameters tell the browser cookie The path of . By default ,cookie Belongs to the current page
document.cookie="username=John Doe; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/";
// stay JavaScript in , modify cookie Similar to creating cookie, As shown below :
document.cookie="username=John Smith; expires=Thu, 18 Dec 2043 12:00:00 GMT; path=/";
// Delete cookie It's simple . You just need to set up expires The parameter is the previous time , As shown below , Set to Thu, 01 Jan 1970 00:00:00 GMT:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 GMT";
// obtain html page cookie Method
const getCookie = (name) => {
let result = document.cookie.match(
'(^|[^;]+)\\s*' + name + '\\s*=\\s*([^;]+)'
)
return result ? result.pop() : ''
}
// If you want to cookie Set to 10 Expires in days , It can be realized in this way
// Get the current time
const date=new Date();
const expiresDays=10;
// take date Set to 10 Days later
date.setTime(date.getTime()+expiresDays*24*3600*1000);
// take userId and userName Two cookie Set to 10 Expires in days
document.cookie="userId=828; userName=hulk; expires="+date.toGMTString();
Encapsulate native
// Add one cookie:addCookie(name,value,expiresHours)
// This function receives 3 Parameters :cookie name ,cookie value , And how many hours after expiration . It is agreed here that expiresHours by 0 Do not set expiration time , That is, when the browser closes cookie Auto disappear .
const addCookie = (name,value,expiresHours) => {
const cookieString=name+"="+escape(value);
// Determine whether to set the expiration time
if(expiresHours>0){
const date = new Date();
date.setTime(date.getTime+expiresHours*3600*1000);
cookieString=cookieString+"; expires="+date.toGMTString();
}
document.cookie=cookieString;
}
// Gets the... Of the specified name cookie value :getCookie(name)
// The return name of this function is name Of cookie value , If not, return null
const getCookie = (name) => {
const strCookie=document.cookie;
const arrCookie=strCookie.split("; ");
for(let i=0;i<arrCookie.length;i++){
let arr=arrCookie[i].split("=");
if(arr[0]==name)return arr[1];
}
return "";
}
// Delete the cookie:deleteCookie(name)
// This function can delete the cookie
const deleteCookie = (name) =>{
const date=new Date();
date.setTime(date.getTime()-10000);
document.cookie=name+"=v; expires="+date.toGMTString();
}
The plug-in USES
js-cookie It's a simple one , Lightweight processing cookies Of js API, Used for processing cookie Related plug-ins
// download
npm install --save js-cookie
// quote
import Cookies from 'js-cookie'
// Create a name name, The corresponding value is value Of cookie, Because no expiration time is set , The default expiration time is when the website is closed
Cookies.set(name, value)
// Create a valid time of 7 Days of cookie
Cookies.set(name, value, {
expires: 7 })
// Create a with a path cookie
Cookies.set(name, value, {
path: '' })
// Create a value For the object cookie
const obj = {
name: 'ryan' }
Cookies.set('user', obj);
// Gets the... Of the specified name cookie
Cookies.get(name) // value
// obtain value For the object cookie
const obj = {
name: 'ryan' }
Cookies.set('user', obj)
JSON.parse(Cookies.get('user'))
// Get all cookie
Cookies.get();
// Delete the cookie
Cookies.remove(name) // value
// Delete... With path cookie
Cookies.set(name, value, {
path: '' })
Cookies.remove(name, {
path: '' })
Web Storage
Web Storage API Provision mechanism , Enable browsers to use in a way that compares Cookie A more intuitive way to store keys / It's worth it .
Web Storage There are two mechanisms :
sessionStorage
For each given source (given origin) Maintain a separate storage area , This storage area is available during the page session ( That is, as long as the browser is open , Including page reload and recovery ).localStorage
Same function , But in the browser close , The data still exists after reopening .
Commonly used API
This method accepts a value n As a parameter , And return... In the storage n A key name .
This method takes a key name as an argument , Return the value corresponding to the key name .
This method takes a key name and value as parameters , Key value pairs will be added to the store , If key name exists , Then update its corresponding value .
This method takes a key name as an argument , And remove the key name from the storage .
Calling this method clears all key names in the store .
Basic use
localStorage.setItem('bgcolor', 'yellow');
localStorage.getItem('bgcolor');
localStorage.removeItem('bgcolor');
localStorage.key(0); // Should return to 'bgcolor'
Web Storage and cookies difference
cookies
- Purpose of creation
- In order to maintain http state
- Data stored locally to identify user information
- characteristic
- Storable size 4k
- The number of storage is limited ( Different browsers )
- The effective time is set at cookies Valid until expiration date
sessionStorage and localStorage
- Purpose of creation
- Easy for client to store data
- The same thing
- It's all by h5 web Storage API Provide
- Keep it locally
- And storage size 5M above
- The validity period is different
- sessionStorage Data is automatically deleted when the current browser window is closed
- localStrong Store persistent data Do not delete data after the browser is closed , Unless you delete it yourself
Common ground Record user status
difference
- cookie
- It adopts the scheme of saving state on the client That is, it runs on the client
- There's a size limit , The number of storage is limited
- There are security risks Tamper with locally stored information by some means to deceive the server
- Support cross domain access
- session
- The solution adopted is to maintain the state on the server That is, it runs on the server
- No size limit is related to the memory size of the server
- Too much will increase server pressure
- Only valid in his domain name
Respective advantages
- cookie
- High scalability and availability
- No need to use a lot of server resources
- simplicity cookie Is a text-based lightweight structure , Include simple key value pairs , Simple structure
- session
- Easy to read and write
- Easy site customization
Common attack methods and Solutions
cookie
- Specifically
- Direct access cookie File line wants confidential information
- Conduct cookie Information is intercepted during transmission
- The attacker faked cookie Information 、 After the client obtains the data, perform the operation
- Solution
- Not in cookie Save sensitive information in
- Not in cookie Save sensitive information that you have not encrypted or that can be easily parsed
- For the... Obtained from customer exchange cookie Strict verification of information
session
- Specifically
- Session hijacking ( By getting users sessionID after , Use this sessionID Log in to the target account )
- The conversation is fixed ( Trick the victim into using the session ID specified by the attacker sessionID The means of attack )
- Solution
- Use user-Agent Check the consistency of the request ; Set up httpOrly, It can prevent client script from accessing this cookie, So as to effectively prevent xss attack ; Turn off transparency + sessionID; change session name
- Generate a new when the user logs in sessionID
边栏推荐
- 2021 CSP J2 entry group csp-s2 improvement group round 2 video and question solution
- Basic violin plot in R with plot
- [noodle classic] Yunze Technology
- Tdengine invitation: be a superhero who uses technology to change the world and become TD hero
- dns备用服务器信息,dns服务器地址(dns首选和备用填多少)
- C语言学习-Day_05
- Arduino PROGMEM静态存储区的使用介绍
- Error im002 when Oracle connects to MySQL
- audiotrack与audioflinger
- 3D移动 translate3d
猜你喜欢
leetcode:968. Monitor the binary tree [tree DP, maintain the three states of each node's subtree, it is very difficult to think of the right as a learning, analogous to the house raiding 3]
Tdengine invitation: be a superhero who uses technology to change the world and become TD hero
Explain the imaging principle of various optical instruments in detail
es 根据索引名称和索引字段更新值
lvi-sam 总结
感应电机直接转矩控制系统的设计与仿真(运动控制matlab/simulink)
详细记录YOLACT实例分割ncnn实现
学习笔记之——数据集的生成
【报名】基础架构设计:从架构热点问题到行业变迁 | TF63
TCP/IP 详解(第 2 版) 笔记 / 3 链路层 / 3.4 桥接器与交换机 / 3.4.1 生成树协议(Spanning Tree Protocol (STP))
随机推荐
Introduction to the use of Arduino progmem static storage area
This application failed to start because it could not find or load the QT platform plugin
【面经】云泽科技
详细记录YOLACT实例分割ncnn实现
以后发现漏洞,禁止告诉中国!
torchvision. models._ utils. Intermediatelayergetter tutorial
BufferedWriter 和 BufferedReader 的使用
[noodle classic] Yunze Technology
R语言使用econocharts包创建微观经济或宏观经济图、demand函数可视化需求曲线(demand curve)、自定义配置demand函数的参数丰富可视化效果
细说物体检测中的Anchors
C language learning day_ 04
Stop using system Currenttimemillis() takes too long to count. It's too low. Stopwatch is easy to use!
torch. utils. data. Randomsampler and torch utils. data. Differences between sequentialsampler
Learning notes - data set generation
Es update values based on Index Names and index fields
【OpenCV 例程200篇】211. 绘制垂直矩形
新旧两个界面对比
[so official interview] Why do developers using rust love it so much
R language uses econcharts package to create microeconomic or macro-economic charts, demand function to visualize demand curve, and customize the parameters of demand function to enrich the visualizat
别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!