当前位置:网站首页>Three cache technologies -- localstorage, sessionstorage, cookies
Three cache technologies -- localstorage, sessionstorage, cookies
2022-07-28 07:04:00 【Hahaha~】
One 、 Client storage
web The application allows the use of API Store the data on the client computer
Client storage complies with “ The same-origin policy ”, Different site pages cannot read each other's data
Between different pages of the same site , The stored data is shared
The storage validity period of data can be temporary , For example, close the browser and destroy the data ; It can also be permanent , You can store any time on the client computer
Two 、Cookie
1) establish cookie:
function setCookie(name, value, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = name + "=" + value + "; " + expires
}
setCookie("haha",123,30)2) obtain cookie:
function getCookie(name) {
var name = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); }
}
return "";
}
// Print all cookie
console.log(document.cookie)3) Judge whether there is a cookie:
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert(" welcome " + user + " Revisit ");
}
else {
user = prompt(" Please enter your name :", "");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}4) example :
<input type="text" id="name">
<input type="text" id="pwd">
<button onclick="fn()"> preservation </button>
<script>
function fn(){
var name = document.querySelector("#name");
var pwd = document.querySelector("#pwd");
var exday = new Date(new Date().getTime()+1000*60*60*24*30)
// The semicolon is preceded by the user's cached content , The following is some settings for these contents ( Validity period, etc )
document.cookie = `name=${name.value}&pwd=${pwd.value};expires=${exday}`;
}
window.onload=function(){
// obtain cookie Value
console.log(document.cookie);
}
</script>
5) expand :
cookie attribute :name、value、expires、domain、path、secure、max-age、HttpOnly.
name:
- name Properties are required , It's a key value pair , Is used to specify the Cookie Key
value:
- value Properties are required , It's a key value pair , Is used to specify the Cookie Value
expires:
- expires Property is used to specify Cookie Expiration time
- It uses UTC or GMT Format adopt new Date().toUTCString() or new Date().toGMTString() obtain
- If this property is not set or set to null,Cookie Valid only in the current session , Once the browser window is closed , At present Session end , The Cookie It will be deleted
- Browser based on local time , decision Cookie Is it overdue , Because the local time is not accurate , So there's no way to guarantee Cookie It will expire at the time specified by the server
- When the set expiration time is greater than or equal to 1 days : Can be in expires Enter directly after the attribute XX Days
Cookies.set('name', 'value', { expires: 7, })
- When the set expiration time is less than one day : You need to add the expiration time to the current time .
// Here are the settings cookie The expiration time of is 15 minute . var m= new Date().getTime() var expiresTime = new Date(m + 60 * 1000 * 15) Cookies.set('name', 'value', { expires: expiresTime, })
- When expires Set a past time point , So this cookie Will be deleted immediately ( invalid )
domain:
- domain Attribute specifies Cookie The domain name Such as baidu.com If not specified, the default setting is Cookie Domain name of
- The specified domain name must be currently sent Cookie Part of the domain name , For example, the domain name you are currently visiting is example.com, You cannot set it to google.com
- Only the domain name visited matches domain attribute ,Cookie Will be sent to the server
path:
- path Property is used to specify the path and must be an absolute path If not specified, the default is to request this Cookie Web page path
- Only path Property matches the path sent to the server ,Cookie Will send
- The match here is not an absolute match , It starts from the root path , as long as path Property matches part of the send path , You can send
- Such as path Attribute is equal to the /blog, Then the sending path is /blog perhaps /blogroll,Cookie Will send
- path The premise for the attribute to take effect is domain Attribute matching
secure:
- secure Property to specify Cookie Only in the encryption protocol HTTPS Send to the server
- This property is just a switch , You do not need to specify a value If the communication is HTTPS Agreement this switch will automatically turn on
max-age:
- max-age Property to specify Cookie The period of validity
- Under normal circumstances ,max-age Has a higher priority than expires, But there are some nuances
HttpOnly:
- HttpOnly Property is used to set the Cookie Can not be JavaScript Read ( namely document.cookie Will not return this Cookie Value )
- Only for sending to the server Mainly to prevent XSS Attack and steal Cookie
3、 ... and 、localStorage and sessionStorage Of API
- setItem(): Pass in the corresponding name and value , Data storage can be realized
- getItem(): Pass the name in , You can get the corresponding value
- removeItem(): Pass the name in , You can delete the corresponding value
- clear(): Delete all cached values , No parameters required
- length: attribute , Get the total number of key value pairs
- key(): Number of incoming locations , Get the name of the stored value
notes :localStorage and sessionStorage yes window Two properties of They represent the same Storage object
Four 、localStorage
- Permanent preservation
- setItem(string key, value): preservation
- getItem(string key): obtain
- clear(): Empty
- removeItem(sring key): Get the value from the key
example :
<input type="text" id="box1">
<button onclick="localStorage1()">LocalStorage Save the data </button>
<button onclick="getlocalStorage1()">LocalStorage Take the data </button>
<button onclick="clear1()">LocalStorage Clear data </button>
<script>
function localStorage1(){
window.localStorage.setItem("username","haha")
window.localStorage.setItem("touxiang"," A link to an image ")
}
function getlocalStorage1(){
var re=window.localStorage.getItem("username")
console.log(re)
}
function clear1(){
window.localStorage.clear()
}
</script>5、 ... and 、sessionStorage
- Close the browser and all data will be deleted automatically
- sessionStorage.length: Returns an integer Indicates stored in sessionStorage Data item in object ( Key value pair ) Number
- sessionStorage.key(int index): Returns the current sessionStorage Object number index Ordinal key name If not, go back null
- sessionStorage.getItem(string key) : Return key name (key) Corresponding value (value) If not, go back null
- sessionStorage.setItem(string key, string value) : Receive a key name (key) And the value (value) As a parameter , Add key value pairs to storage ; If key name exists , Then update its corresponding value
- sessionStorage.removeItem(string key) : Will specify the key name (key) from sessionStorage Remove from object
- sessionStorage.clear() : eliminate sessionStorage All the items of the object
example ( And localStorage be similar ):
<input type="text" id="box1">
<button onclick="sessionStorage()">sessionStorage Save the data </button>
<button onclick="sessionStorage1()">sessionStorage Take the data </button>
<button onclick="clear1()">sessionStorage Clear data </button>
<script>
function sessionStorage1() {
window.sessionStorage.setItem("username", "haha")
window.sessionStorage.setItem("touxiang", " A link to an image ")
}
function getsessionStorage1() {
var re = window.sessionStorage.getItem("username")
console.log(re)
}
function clear1() {
window.sessionStorage.clear()
}
</script>6、 ... and 、localStorage and sessionStorage The difference between
(1) Valid time :
- localStorage: The stored data is permanent , Users can actively clear these cached data : Such as clearing history
- sessionStorage: The stored data is lost when the window or label is closed ; Data will not be lost when a tag moves forward or backward
(2) Scope :
- localStorage The scope of is limited to the document source : Document source is agreement 、 domain name 、 Ports are determined by three
- localStorage Homologous documents can access and modify data with the same name
- localStorage Limited by browser manufacturers ,chrome Stored data 360 Browser inaccessible You'll get ‘Invalid Date’
- sessionStorage stay localStorage Based on the homologous strategy , There are stricter restrictions :
- He was also confined to the window , It means that different pages of the same window or tab can be shared sessionStorage
- But different windows or tabs cannot be shared sessionStorage, Even if they are the same page address
- Windows are top-level windows , If more than one iframe, They share it with each other sessionStorage
7、 ... and 、localStorage、sessionStorage、Cookie Differences among the three
(1) Storage size :
- cookie Data size cannot exceed 4k
- sessionStorage and localStorage Although there are also storage size limitations , But more than cookie Much more , You can achieve 5M Or bigger
(2) Valid time :
- localStorage: Store persistent data , Data will not be lost after the browser is closed unless data is actively deleted
- sessionStorage: Data is automatically deleted when the current browser window is closed
- cookie: Set up cookie Valid until expiration date , Even if the window or browser is closed
(3) The interaction between data and server :
- cookie The data will be automatically delivered to the server , The server can also write cookie To client
- sessionStorage and localStorage It doesn't automatically send data to the server , Save locally only
(4) Scope :
- localStorage The scope of is limited to the... Of the document source
- localStorage Homologous documents can access and modify data with the same name
- localStorage Limited by browser manufacturers :chrome Data stored under ,360 Not accessible under the browser
- sessionStorage stay localStorage Based on the homologous strategy , There are stricter restrictions : Restricted to window
- That is, different pages of the same window or tab can be shared sessionStorage, But different windows or tabs cannot be shared sessionStorage, Even if they are the same page address
- The window here is a top-level window , If there are multiple iframe, They share it with each other sessionStorage
边栏推荐
- QT使用MSVC编译器输出中文乱码问题
- Test interview questions collection (V) | automated testing and performance testing (with answers)
- VMware Workstation 配置net模式
- MOOC翁恺C语言第五周:1.循环控制2.多重循环3.循环应用
- Firewall - iptables firewall (four tables and five links, firewall configuration method, detailed explanation of matching rules)
- FTP service
- 静态和浮动路由
- Es6--- > arrow function, class, modularization
- Cocos2d-x learning notes Tile Map tiledmap
- Qgraphicsview promoted to qchartview
猜你喜欢

MOOC翁恺C语言第七周:数组运算:1.数组运算2.搜索3.排序初步

DNS域名解析

YUM仓库的搭建

DNS forward resolution experiment

Cocos2d-x learning notes Tile Map tiledmap

Wechat applet custom compilation mode

Blue bridge code error ticket

MOOC翁恺C语言 第六周:数组与函数:1.数组2.函数的定义与使用3.函数的参数和变量4.二维数组

Applet navigator cannot jump (debug)

Esxi community network card driver
随机推荐
DNS domain name resolution
Hdu-5806-nanoapelovesequence Ⅱ (ruler method)
How to describe a bug and the definition and life cycle of bug level
MOOC翁恺C语言第八周:指针与字符串:1.指针2.字符类型3.字符串4.字符串计算
[learning notes] tool
静态和浮动路由
Pku-2524-ubiquitous relations (parallel search template)
Insertion and deletion of nodes in linked list
Pku-2739-sum of constructive prime numbers
DOM - Events
Test interview questions collection (I) | common required questions and procedures of software testing (with answers)
Network - data link layer
Technology sharing | detailed explanation of actual combat interface test request methods get, post
小甲鱼C(第六章数组1、2)
Repair the faulty sector
Animation animation realizes the crossing (click) pause
Blue bridge code error ticket
Shell script - regular expression
DHCP服务
1、 PXE overview and installation