两者都是在浏览器中存储内容,用于前后端通信
cookie
cookie基本概念,作用
cookie浏览器存储数据的方式,本地存储,可以发送给服务端
cookie的属性
名称,值,时间,域,路径
设置了 HttpOnly 属性的 Cookie 不能通过 JS 去访问
Secure 安全标志: Secure 限定了只有在使用了 https 而不是 http 的情况下才可以发送给服务端
Domain、Path、Secure 都要满足条件,还不能过期的 Cookie 才能随着请求发送到服务器端
script>
//写cookie
//打开网页的方式不同,会影响网页是否能查看cookie
document.cookie="age=18";
// //读cookie
console.log( document.cookie);
// cookie的名称和值的设置,最好不用中文
document.cookie='性别=男';
document.cookie=`${encodeURIComponent('爱好')}=${encodeURIComponent('睡觉')}`;
// 设置cookie存在时间
// cookie.setHttpOnly(false);
document.cookie=`name=xiaoming;expires=${new Date('2100-1-01 00:00:00')}`;
// 删除cookie可以把max-age设置为零
document.cookie=`hobby=sleep;max-age=100`;
// 设置cookie的域,只能访问当前域以及父域,该域是不可以访问的,所以无法设置cookie
//当前域www.imooc.com,父域.imooc.com
document.cookie=`data=42;domain=www.imooc.com`
// path只能写入当前路径 http://127.0.0.1:5500/writecookie.html,可以从下往上访问路径
document.cookie=`moon=happy`;
// 只有当name domain,path都一样的时候,才是同一个cookie
</script>
cookie的封装set,get,remove
cookie.js文件
//写入cookie
const set=(name,value,{maxAge,domain,path,secure}={})=>{
let cookieText=`${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
//对剩余属性的的设置
if(typeof maxAge ==='number'){
cookieText+=`;max-age=${maxAge}`;
}
if(domain){
cookieText+=`;domain=${domain}`;
}
if(path){
cookieText+=`;path=${path}`;
}
if(secure){
cookieText+=`;secure`;
}
document.cookie=cookieText;
};
// 通过 name 获取 cookie 的值
const get = name => {
name = `${encodeURIComponent(name)}`;
const cookies = document.cookie.split('; ');
for (const item of cookies) {
const [cookieName, cookieValue] = item.split('=');
if (cookieName === name) {
return decodeURIComponent(cookieValue);
}
}
return;
};
// 根据 name、domain 和 path 删除 Cookie
const remove = (name, { domain, path } = {}) => {
set(name, '', { domain, path, maxAge: -1 });
};
//将写好的函数暴露出去
export {set,get,remove};
cookie应用
中英文的切换
<div id="btncn">中文</div>
<div id="btnen">英文</div>
<script type="module">
import {set,get,remove} from './cookie.js';
const oBtncn =document.getElementById('btncn');
// console.log(oBtncn);
const oBtnen =document.getElementById('btnen');
oBtncn.addEventListener('click', function(){
set('language','cn',{maxAge:30*24*3600});
//当前网站强制刷新
window.location = './index.html';
},false);
oBtnen.addEventListener('click', function(){
set('language','en',{maxAge:30*24*3600});
window.location = './index.html';
},false);
</script>
cookie的注意事项
cookie有大小和数量的限制
localStorage
<script>
console.log(localStorage);
//基本用法
localStorage.setItem('name','xiaoming');
localStorage.setItem('age',18);
//length
console.log(localStorage.length);
//获取不存在的返回null
console.log(localStorage.getItem('name'));
//删除
localStorage.removeItem('name');
console.log(localStorage.getItem('name'));
//全部删除
localStorage.clear();
console.log(localStorage.length);
</script>