cookie 本地存储

Cookie

  • 浏览器存储数据的一种方式
  • 存储在用户本地,而不是存储在服务器上
  • 可以随着浏览器每次请求发送到服务器端

初识cookie

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>初识 Cookie</title>
  </head>
  <body>
    <script>
    // 1.Cookie 是什么
    // Cookie 全称 HTTP Cookie,简称 Cookie
    // 是浏览器存储数据的一种方式
    // 因为存储在用户本地,而不是存储在服务器上,是本地存储
    // 一般会自动随着浏览器每次请求发送到服务器端

    // 2.Cookie 有什么用
    // 利用 Cookie 跟踪统计用户访问该网站的习惯,比如什么时间访问,访问了哪些页面,在每个网页的停留时间等

    // 3.在浏览器中操作 Cookie
    // 不要在 Cookie 中保存密码等敏感信息
    </script>
  </body>
</html>

cookie的基本用法

  • 写入cookie
document.cookie = 'username=alex;max-age=5';
document.cookie = 'age=18;domain=.imooc.com;max-age=5';
  • 读取cookie
document.cookie; //username=alex;age=18
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Cookie 的基本用法</title>
  </head>
  <body>
    <script>
      // 1.写入 Cookie
      // document.cookie = 'username=zs';
      // document.cookie = 'age=18';

      // 不能一起设置,只能一个一个设置
      // document.cookie = 'username=zs; age=18';

      // 2.读取 Cookie
      console.log(document.cookie);

      // 读取的是一个由名值对构成的字符串,每个名值对之间由“; ”(一个分号和一个空格)隔开
      // username=zs; age=18
    </script>
  </body>
</html>

Cookie 的属性

  • 名称( Name)和值(Value)
    • 创建 Cookie 时必须填写,其它属性可以使用默认值
    • 如果包含非英文字母,写入时要用 encodeURIComponent() 编码
    • 如果写入时编码,读取时要用 decodeURIComponent() 解码

。失效(到期)时间

  • 失效的 Cookie,会被浏览器清除
  • 如果没有设置失效时间,默认会话结束后,Cookie 会被清除
  • 想 Cookie 长时间存在,可以设置 Expires 或 Max-Age
  • Expires 值为 Date 类型,表示具体什么时间过期
  • Max-Age 值为数字,表示当前时间加多少秒后过期,单位是秒
  • 如果设置 Max-Age 的值是 0 或负数,则 Cookie 会被删除
  • Domain
    • Domain 限定了访问 Cookie 的范围(不同域下)
    • 使用 JS 只能写入/读取当前域或父域的 Cookie,无法写入/读取其他域的 Cookie
  • Path
    • Path 限定了访问 Cookie 的范围(同域不同路径下)
    • 使用 JS 只能写入/读取当前路径和上级路径的 Cookie,无法写入/读取其他路径的 Cookie
  • 当 Name、Domain、Path 这 3 个字段都相同的时候,才是同一个 Cookie
  • HttpOnly
    • 前端不能通过 JS 去设置一个 HttpOnly 类型的 Cookie,这种类型的 Cookie 只能是后端来设置
    • 只要是 HttpOnly 类型的,通过 document.cookie 是获取不到的,也不能进行修改
  • Secure
    • Secure 限定了只有在使用了 https 而不是 http 的情况下才可以发送给服务端
  • Domain、Path、Secure 都要满足条件,还不能过期的 Cookie才能随着请求发送到服务器端
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Cookie 的属性</title>
  </head>
  <body>
    <script>
      // 1.Cookie 的名称(Name)和值(Value)
      // 最重要的两个属性,创建 Cookie 时必须填写,其它属性可以使用默认值

      // Cookie 的名称或值如果包含非英文字母,则写入时需要使用 encodeURIComponent() 编码,读取时使用 decodeURIComponent() 解码
      document.cookie = 'username=alex';

      document.cookie = `username=${encodeURIComponent('张三')}`;
      document.cookie = `${encodeURIComponent('用户名')}=${encodeURIComponent(
        '张三'
      )}`;

      // 一般名称使用英文字母,不要用中文,值可以用中文,但是要编码

      // 2.失效(到期)时间
      // 对于失效的 Cookie,会被浏览器清除
      // 如果没有设置失效(到期)时间,这样的 Cookie 称为会话 Cookie
      // 它存在内存中,当会话结束,也就是浏览器关闭时,Cookie 消失

      document.cookie = 'username=alex';

      // 想长时间存在,设置 Expires 或 Max-Age
      // expires
      // 值为 Date 类型
      document.cookie = `username=alex; expires=${new Date(
        '2100-1-01 00:00:00'
      )}`;

      // max-age
      // 值为数字,表示当前时间 + 多少秒后过期,单位是秒
      document.cookie = 'username=alex; max-age=5';
      document.cookie = `username=alex; max-age=${24 * 3600 * 30}`;

      // 如果 max-age 的值是 0 或负数,则 Cookie 会被删除
      document.cookie = 'username=alex';
      document.cookie = 'username=alex; max-age=0';
      document.cookie = 'username=alex; max-age=-1';

      // 3.Domain 域
      // Domain 限定了访问 Cookie 的范围(不同域名)

      // 使用 JS 只能读写当前域或父域的 Cookie,无法读写其他域的 Cookie
      document.cookie = 'username=alex; domain=www.imooc.com';

      // www.imooc.com m.imooc.com 当前域
      // 父域:.imooc.com

      // 4.Path 路径
      // Path 限定了访问 Cookie 的范围(同一个域名下)

      // 使用 JS 只能读写当前路径和上级路径的 Cookie,无法读写下级路径的 Cookie
      document.cookie = 'username=alex; path=/course/list';
      document.cookie = 'username=alex; path=/1.Cookie/';

      // 当 Name、Domain、Path 这 3 个字段都相同的时候,才是同一个 Cookie

      // 5.HttpOnly
      // 设置了 HttpOnly 属性的 Cookie 不能通过 JS 去访问

      // 6.Secure 安全标志
      // Secure 限定了只有在使用了 https 而不是 http 的情况下才可以发送给服务端

      // Domain、Path、Secure 都要满足条件,还不能过期的 Cookie 才能随着请求发送到服务器端
    </script>
  </body>
</html>

 cookie的封装

// 写入 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;

  // document.cookie='username=alex; max-age=5; domain='
};

// 通过 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;
};

// 'username=alex; age=18; sex=male'
// ["username=alex", "age=18", "sex=male"]
// ["username","alex"]

// get('用户名');

// 根据 name、domain 和 path 删除 Cookie
const remove = (name, { domain, path } = {}) => {
  set(name, '', { domain, path, maxAge: -1 });
};

export { set, get, remove };
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Cookie 的封装</title>
  </head>
  <body>
    <button id="cn">中文</button>
    <button id="en">英文</button>

    <script type="module">
      import { set, get, remove } from './cookie.js';
      import { set, get, remove } from './cookie.js';
      set('username', 'alex');
      set('username', 'zs');
      set('age', 18);
      set('用户名', '张三');

      set('sex', 'male', {
        maxAge: 30 * 24 * 3600
      });

      remove('username');
      remove('用户名');

      console.log(get('username'));
      console.log(get('age'));
      console.log(get('用户名'));
      console.log(get('sex'));

      // 使用封装好的 Cookie 实现网站语言切换
      import { set } from './cookie.js';
      const cnBtn = document.getElementById('cn');
      const enBtn = document.getElementById('en');

      cnBtn.addEventListener(
        'click',
        () => {
          set('language', 'cn', {
            maxAge: 30 * 24 * 3600
          });
          window.location = './2-6.Cookie 的封装.html';
        },
        false
      );
      enBtn.addEventListener(
        'click',
        () => {
          set('language', 'en', {
            maxAge: 30 * 24 * 3600
          });
          window.location = './2-6.Cookie 的封装.html';
        },
        false
      );
    </script>
  </body>
</html>

cookie注意事项

  • 前后端都可以写入和获取 Cookie
  • 每个域名下的 Cookie 数量有限
  • 每个 Cookie 的存储容量很小,最多只有 4KB 左右
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Cookie 的注意事项</title>
  </head>
  <body>
    <script>
      // 1.前后端都可以创建 Cookie

      // 2.Cookie 有数量限制
      // 每个域名下的 Cookie 数量有限

      // 当超过单个域名限制之后,再设置 Cookie,浏览器就会清除以前设置的 Cookie

      // 3.Cookie 有大小限制
      // 每个 Cookie 的存储容量很小,最多只有 4KB 左右
    </script>
  </body>
</html>

localStorage

  • 浏览器存储数据的一种方式
  • 存储在用户本地,不会发送到服务器端
  • 单个域名下的总大小有限制(一般最大 5M左右)
  • setItem()
    • localStorage.setItem(‘username’:‘alex’);
  • getItem()
    • localStorage.getItem(‘username’);
  • removeItem()
    • localStorage.removeItem()
  • clear()
    • localStorage.clear()
  • length
    • localStorage.length

初识 localStorage

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>初识 localStorage</title>
  </head>
  <body>
    <form id="login" action="https://www.imooc.com" method="post">
      <input type="text" name="username" />
      <input type="password" name="password" />
      <input type="submit" id="btn" value="登录" />
    </form>

    <script>
      // 1.localStorage 是什么
      // localStorage 也是一种浏览器存储数据的方式(本地存储),它只是存储在本地,不会发送到服务器端

      // 单个域名下的 localStorage 总大小有限制

      // 2.在浏览器中操作 localStorage

      // 3.localStorage 的基本用法
      console.log(localStorage);

      // // setItem()
      localStorage.setItem('username', 'alex');
      localStorage.setItem('username', 'zs');
      localStorage.setItem('age', 18);
      localStorage.setItem('sex', 'male');

      // // length
      console.log(localStorage.length);

      // // getItem()
      console.log(localStorage.getItem('username'));
      console.log(localStorage.getItem('age'));

      // 获取不存在的返回 null
      console.log(localStorage.getItem('name'));

      // // removeItem()
      localStorage.removeItem('username');
      localStorage.removeItem('age');

      // // // 删除不存在的 key,不报错
      // // localStorage.removeItem('name');

      // // clear()
      localStorage.clear();

      console.log(localStorage);

      // 4.使用 localStorage 实现自动填充
      const loginForm = document.getElementById('login');
      const btn = document.getElementById('btn');

      const username = localStorage.getItem('username');
      if (username) {
        loginForm.username.value = username;
      }

      btn.addEventListener(
        'click',
        e => {
          e.preventDefault();
          // 数据验证

          // console.log(loginForm.username.value);

          localStorage.setItem('username', loginForm.username.value);

          loginForm.submit();
        },
        false
      );
    </script>
  </body>
</html>

localStorage 的注意事项

  • localStorage 存储的数据,除非手动清除,否则永远存在
  • sessionStorage 存储的数据,当会话结束时就会被清除
  • localStorage 存储的键和值只能是字符串类型
  • 不同的域名不能共用 localStorage
  • IE7及以下版本不支持 localStorage,IE8 开始支持
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>localStorage 的注意事项</title>
  </head>
  <body>
    <script>
      // 1.localStorage 的存储期限
      // localStorage 是持久化的本地存储,除非手动清除(比如通过 js 删除,或者清除浏览器缓存),否则数据是永远不会过期的

      // sessionStorage
      // 当会话结束(比如关闭浏览器)的时候,sessionStorage 中的数据会被清空
      sessionStorage.setItem('username', 'alex');
      sessionStorage.getItem('username');
      sessionStorage.removeItem('username');
      sessionStorage.clear();

      // 2.localStorage 键和值的类型
      // localStorage 存储的键和值只能是字符串类型
      // 不是字符串类型,也会先转化成字符串类型再存进去

      localStorage.setItem({}, 18);
      // localStorage.setItem('students', [{},{}]);
      console.log(
        typeof localStorage.getItem('[object Object]'),
        localStorage.getItem('[object Object]')
      );

      // console.log({}.toString()); //[object Object]

      // 3.不同域名下能否共用 localStorage
      // 不同的域名是不能共用 localStorage 的

      // 4.localStorage 的兼容性
      // IE7及以下版本不支持 localStorage,IE8 开始支持

      // caniuse.com
    </script>
  </body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值