1 , cookie的查找
document.cookie
2 , cookie的设置
document.cookie = 'user = "hhh"'
3 , 完整的cookie
'user=值; expires=失效时间; path=路径访问; domain=域名访问; secure= 安全的https限制通信' ;
4 , cookie的删除
将失效时间设置为已过时间
document.cookie = 'user="hhh"; expires=new Date(0) ;
5 , 其他的存储
localStorage、sessionStorage
(1) , 设置
setItem('name' , 'lee') ;
(2) , 获取
getItem('name') ;
(3) , 删除
removeItem('name') ;
<!--监控其数据变化-->
window.onstorage = function(){
}
<!--
let cookie = {
//获取cookie
getCookie:function (name) {
//获取所有的cookie
let allCookie = document.cookie ;
let arr = allCookie.split('; ') ;
for (let i = 0 ; i < arr.length ; i++){
let newArr = arr[i].split('=') ;
if (newArr[0] === name) {
return decodeURIComponent(newArr[1]) ;
}
}
} ,
//设置cookie
setCookie:function (name , value , expires , path , domain , secure) {
let cookieName = encodeURIComponent(name) + '=' +encodeURIComponent(value);
if (expires instanceof Date){
cookieName += '; expires=' + expires ;
}
if (path){
cookieName += '; path' + path;
}
if (domain){
cookieName += '; domain' + domain ;
}
if (secure){
cookieName += '; secure' ;
}
document.cookie = cookieName ;
} ,
//删除cookie
delCookie:function (name) {
let data = new Date(new Date().getTime() - 1).toGMTString() ; //设置时间
document.cookie = `${name} ='' ; expires = ${data}` ;
}
} ;
function setCookieDate(day) {
let date = null ;
if (typeof day === 'number' && day > 0 ){
date = new Date() ;
date.setDate(date.getDate() + day) ;
} else{
throw new Error('传递的天数不合法!必须是大于0的数字') ;
}
return date ;
}
-->
Cookie
最新推荐文章于 2022-07-14 12:57:15 发布