废话不说直接上代码
cookie.js
点击查看代码
const set = (name,value,{maxAge,domain,path,secure} = {}) => {
let cookieStr = `${encodeURIComponent(name)} = ${encodeURIComponent(value)}`;
if(typeof maxAge == 'number'){
cookieStr += `; max-age = ${maxAge}`;
}
if(domain){
cookieStr += `; domain = ${domain}`;
}
if(path){
cookieStr += `; path = ${path}`;
}
if(typeof secure == 'boolean'){
if(secure == true)
cookieStr += '; secure';
}
console.log(cookieStr);
document.cookie = cookieStr;
return true;
}
const get = name => {
name = encodeURIComponent(name);
const cookieArray = document.cookie.split('; ');
for (const item of cookieArray) {
const [cookieName,cookieValue] = item.split('=');
if(cookieName == name){
return decodeURIComponent(cookieValue);
}
}
return false;
}
const remove = (name,{domain,path} = {}) => {
if(name == undefined||domain == undefined || path == undefined){
// console.log(name);
// console.log(domain);
// console.log(path);
return false;
}
name = encodeURIComponent(name);
return set(name,'',{
domain,
path,
maxAge:-1,
});
}
export {set,get,remove}
html展示
点击查看代码
<!DOCTYPE html>
<html lang="en">
<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>Cookie的封装</title>
</head>
<body>
<script type="module">
import {set,get,remove} from './cookie.js'
set('user','lsh');
set('用户','李世海');
set('年龄','永远的18岁!',{
maxAge:999999999,
});
set('secure','value',{
secure:true,
})
// 展示出来
const userH2 = document.createElement('h2');
const userChineseH2 = document.createElement('h2');
const ageChineseH2 = document.createElement('h2');
const secureH2 = document.createElement('h2');
// 挂载节点
const boday = document.getElementsByTagName('body')[0];
remove('user',{
domain:'127.0.0.1',
path:'/',
})
userH2.innerText = get('user');
userChineseH2.innerText = get('用户');
ageChineseH2.innerText = get('年龄');
secureH2.innerText = get('sevure');
boday.appendChild(userH2);
boday.appendChild(userChineseH2);
boday.appendChild(ageChineseH2);
boday.appendChild(secureH2);
</script>
</body>
</html>
总结
原生方式
添加
document.cookie = 'name=lsh; max-age=9999; domain=.taobao.com; path=/posts; secure'
document.cookie = '名=值; 属性名=属性值; 属性名=属性值; 属性名=属性值; secure'
secure 只要写上属性名就生效
doamin 值中的.taobao.com和taobao.com作用不同,.taobao.com代表以taobao.com为根域名的二、三级域名都可以访问,taobao.com仅仅代表自身
path 值中的/pages和/pages/作用相同,但不视为同一(名/值)对,可同时存在
max-age = -1或0,可removecookie中对应的那一项
cookie中name,domain,path三者相同视为替换