当前位置:网站首页>JS client storage

JS client storage

2022-06-27 10:17:00 Xiaaoke

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

  • Storage.key()

    This method accepts a value n As a parameter , And return... In the storage n A key name .

  • Storage.getItem()

    This method takes a key name as an argument , Return the value corresponding to the key name .

  • Storage.setItem()

    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 .

  • Storage.removeItem()

    This method takes a key name as an argument , And remove the key name from the storage .

  • Storage.clear()

    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
原网站

版权声明
本文为[Xiaaoke]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206270914371762.html