cookie和localStorage

本文详细介绍了Cookie的基本概念、属性及其在浏览器中的使用,包括设置、读取和删除Cookie的方法,并提供了封装好的Cookie操作函数。同时,文章提到了LocalStorage的基本操作和应用场景,如中英文切换。最后,讨论了Cookie的限制和注意事项,以及LocalStorage的特点。
摘要由CSDN通过智能技术生成

两者都是在浏览器中存储内容,用于前后端通信

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值