1.Cookie

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

1.1 Cookie的用法

1.1.1 写入 Cookie

document.cookie = 'username=zs';
document.cookie = 'age=18';

cookie的名称或值如果包含非英文字母,则写入时需要使用encodeURIComponent编码,读取时需要使用解码。

document.cookie = `username=${encodeURIComponent('张三')}`;
document.cookie = `${encodeURIComponent('性别')}=${encodeURIComponent('男')}`;

1.1.2 读取 Cookie

console.log(document.cookie);
console.log(decodeURIComponent(document.cookie));

输出结果:

username=%E5%BC%A0%E4%B8%89; %E6%80%A7%E5%88%AB=%E7%94%B7
index.html:25 username=张三; 性别=男

1.2 Cookie 的属性

1.2.1 名称( Name)和值(Value)

  • 创建 Cookie 时必须填写,其它属性可以使用默认值;
  • 如果包含非英文字母,写入时要用 encodeURIComponent() 编码;
  • 如果写入时编码,读取时要用 decodeURIComponent() 解码。
// 创建 Cookie 
document.cookie = `username=${encodeURIComponent('张三')}`;
// 读取 Cookie
console.log(decodeURIComponent(document.cookie));

1.2.2 失效(到期)时间

  • 失效的 Cookie,会被浏览器清除;
  • 如果没有设置失效时间,默认会话结束后,Cookie 会被清除;
  • 想 Cookie 长时间存在,可以设置 Expires 或 Max-Age;
  • Expires 值为 Date 类型,表示具体什么时间过期;
  • Max-Age 值为数字,表示当前时间加多少秒后过期,单位是秒;
  • 如果设置 Max-Age 的值是 0 或负数,则 Cookie 会被删除。
document.cookie = `username=zs;expires=${new Date('2021-11-08 07:46:00')}`;
// 缓存3秒
document.cookie = "username=zhangsan;max-age=3";
// 缓存30天
document.cookie = `username=zhangsan;max-age=${24 * 3600 * 30}`;
//删除cookie
document.cookie = "username=zhangsan;max-age=0";

1.2.3 Domain

  • Domain 限定了访问 Cookie 的范围(不同域下);
  • 使用 JS 只能写入/读取当前域或父域的 Cookie,无法写入/读取其他域的 Cookie。
document.cookie = "username=zs;domain=www.abc.com"

1.2.4 Path

  • Path 限定了访问 Cookie 的范围(同域不同路径下);
  • 使用 JS 只能写入/读取当前路径和上级路径的 Cookie,无法写入/读取其他路径的 Cookie。
document.cookie = "username=zs;domain=www.abc.com;path=/admin"

需要注意的是:当 Name、Domain、Path 这 3 个字段都相同的时候,才是同一个 Cookie。

1.2.5 HttpOnly

  • 前端不能通过 JS 去设置一个 HttpOnly 类型的 Cookie,这种类型的 Cookie 只能是后端来设置;
  • 只要是 HttpOnly 类型的,通过 document.cookie 是获取不到的,也不能进行修改。

1.2.6 Secure

Secure 限定了只有在使用了 https 而不是 http 的情况下才可以发送给服务端。
Domain、Path、Secure 都要满足条件,还不能过期的 Cookie才能随着请求发送到服务器端。

1.3 Cookie 的封装

index.html

<script type="module">
        import { set, get, remove } from './cookie.js';
        set('username', 'daixiang');
        set('sex', 'male', {
            maxAge: 24 * 3600 * 1,
            domain: '127.0.0.1'
        });
        console.log(get('username'));
        console.log(get('sex'));
        remove('sex', {
            domain: 'abc.com',
            path: '/'
        });
        console.log(get('username'));
        console.log(get('sex'));
	</script>

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获取value
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;
}
// 删除cookie
const remove = (name, { domain, path } = {}) => {
    set(name, '', { maxAge: 0, domain, path });
}
export { set, get, remove };

1.4 Cookie 的注意事项

  • 每个域名下的 Cookie 数量有限;
  • 每个 Cookie 的存储容量很小,最多只有 4KB 左右。

2.localStorage

  • 浏览器存储数据的一种方式
  • 存储在用户本地,不会发送到服务器端
  • 单个域名下的总大小有限制(一般最大 5M左右)

2.1 localStorage 的基本用法

setItem()

localStorage.setItem('username', 'admin');

getItem()

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

removeItem()

localStorage.removeItem('username');

clear()

localStorage.clear();

length

console.log(localStorage.length);

2.2 localStorage的封装

index.html

<script type="module">
        import { set, get, remove, clear } from './storage.js';
        set('username', 'zhangsan');
        set('hobby', ['A', 'B']);
        console.log(get('hobby'));
    </script>

storage.js

const storage = window.localStorage;
const set = (key, value) => {
    storage.setItem(key, JSON.stringify(value));
}
const get = (key) => {
    return JSON.parse(storage.getItem(key));
}
const remove = (key) => {
    storage.removeItem(key);
}
const clear = () => {
    storage.clear();
}
export { set, get, remove, clear };

2.3 localStorage 的注意事项

  • localStorage 存储的数据,除非手动清除,否则永远存在;
  • sessionStorage 存储的数据,当会话结束时就会被清除;
  • localStorage 存储的键和值只能是字符串类型;
  • 不同的域名不能共用 localStorage;
  • IE7及以下版本不支持 localStorage,IE8 开始支持

3. SessionStorage

同localStorage,但是sessionStorage 存储的数据,当会话结束时就会被清除。