一、Cookie
1、Cookie是什么
Cookie 全稱是HTTP Cookie 簡(jiǎn)稱Cookie 是瀏覽器存儲(chǔ)數(shù)據(jù)的一種方式
- Cookie存儲(chǔ)在用戶本地,而不是存儲(chǔ)在服務(wù)器上,是本地存儲(chǔ)
- 一般會(huì)自動(dòng)隨著瀏覽器每次請(qǐng)求發(fā)送到服務(wù)器端
2、Cookie有什么用
- 利用Cookie跟蹤同級(jí)用戶訪問(wèn)該網(wǎng)站的習(xí)慣,例如什么四件訪問(wèn),訪問(wèn)了哪些頁(yè)面,在每個(gè)網(wǎng)頁(yè)停留的時(shí)間
3、在瀏覽器中操作cookie
查看隨著請(qǐng)求在請(qǐng)求頭中發(fā)送到服務(wù)器

image.png
在控制臺(tái)查看站點(diǎn)對(duì)應(yīng)的cookie值

image.png
4、寫(xiě)入 Cookie
不能一起設(shè)置,只能一個(gè)一個(gè)設(shè)置
document.cookie = 'username=zs';
document.cookie = 'age=18';
// 錯(cuò)誤寫(xiě)法
// document.cookie = 'username=zs; age=18';
5、讀取cookie
讀取的是一個(gè)由名值對(duì)構(gòu)成的字符串,每個(gè)名值對(duì)之間由“; ”(一個(gè)分號(hào)和一個(gè)空格)隔開(kāi)
username=zs; age=18
console.log(document.cookie);
6、Cookie 的名稱(Name)和值(Value)
最重要的兩個(gè)屬性,創(chuàng)建 Cookie 時(shí)必須填寫(xiě),其它屬性可以使用默認(rèn)值
Cookie 的名稱或值如果包含非英文字母,則寫(xiě)入時(shí)需要使用 encodeURIComponent() 編碼,讀取時(shí)使用 decodeURIComponent() 解碼
document.cookie = 'username=alex';
document.cookie = `username=${encodeURIComponent('張三')}`;
document.cookie = `${encodeURIComponent('用戶名')}=${encodeURIComponent(
'張三'
)}`;
一般名稱使用英文字母,不要用中文,值可以用中文,但是要編碼
7、失效時(shí)間
- 對(duì)于失效的 Cookie,會(huì)被瀏覽器清除
- 如果沒(méi)有設(shè)置失效(到期)時(shí)間,這樣的 Cookie 稱為會(huì)話 Cookie
- 它存在內(nèi)存中,當(dāng)會(huì)話結(jié)束,也就是瀏覽器關(guān)閉時(shí),Cookie 消失
- 想長(zhǎng)時(shí)間存在,設(shè)置 Expires 或 Max-Age
expires值為 Date 類型
document.cookie = `username=alex; expires=${new Date(
'2100-1-01 00:00:00'
)}`;
max-age值為數(shù)字,表示當(dāng)前時(shí)間 + 多少秒后過(guò)期,單位是秒
document.cookie = 'username=alex; max-age=5';
document.cookie = `username=alex; max-age=${24 * 3600 * 30}`;\
如果 max-age 的值是 0 或負(fù)數(shù),則 Cookie 會(huì)被刪除
document.cookie = 'username=alex';
document.cookie = 'username=alex; max-age=0';
document.cookie = 'username=alex; max-age=-1';
8、Domain 域:Domain 限定了訪問(wèn) Cookie 的范圍(不同域名)
使用 JS 只能讀寫(xiě)當(dāng)前域或父域的 Cookie,無(wú)法讀寫(xiě)其他域的 Cookie
document.cookie = 'username=alex; domain=www.imooc.com';
// www.imooc.com m.imooc.com 當(dāng)前域
// 父域:.imooc.com
9、Path 路徑 :Path 限定了訪問(wèn) Cookie 的范圍(同一個(gè)域名下)
- 使用 JS 只能讀寫(xiě)當(dāng)前路徑和上級(jí)路徑的 Cookie,無(wú)法讀寫(xiě)下級(jí)路徑的 Cookie
- 當(dāng) Name、Domain、Path 這 3 個(gè)字段都相同的時(shí)候,才是同一個(gè) Cookie
document.cookie = 'username=alex; path=/course/list';
document.cookie = 'username=alex; path=/1.Cookie/';
10、 HttpOnly :設(shè)置了 HttpOnly 屬性的 Cookie 不能通過(guò) JS 去訪問(wèn)
11、Secure 安全標(biāo)志
- Secure 限定了只有在使用了 https 而不是 http 的情況下才可以發(fā)送給服務(wù)端
- Domain、Path、Secure 都要滿足條件,還不能過(guò)期的 Cookie 才能隨著請(qǐng)求發(fā)送到服務(wù)器端
12、cookie的封裝
// 寫(xiě)入 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='
};
// 通過(guò) 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('用戶名');
// 根據(jù) name、domain 和 path 刪除 Cookie
const remove = (name, { domain, path } = {}) => {
set(name, '', { domain, path, maxAge: -1 });
};
export { set, get, remove };
13、cookie的注意事項(xiàng)
- 前后端都可以創(chuàng)建 Cookie
- Cookie 有數(shù)量限制
- 每個(gè)域名下的 Cookie 數(shù)量有限
- 當(dāng)超過(guò)單個(gè)域名限制之后,再設(shè)置 Cookie,瀏覽器就會(huì)清除以前設(shè)置的 Cookie
- Cookie 有大小限制
- 每個(gè) Cookie 的存儲(chǔ)容量很小,最多只有 4KB 左右
二、localStorage
1、localStorage 是什么
localStorage 也是一種瀏覽器存儲(chǔ)數(shù)據(jù)的方式(本地存儲(chǔ)),它只是存儲(chǔ)在本地,不會(huì)發(fā)送到服務(wù)器端
單個(gè)域名下的 localStorage 總大小有限制
2、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,不報(bào)錯(cuò)
// localStorage.removeItem('name');
// clear()
localStorage.clear();
console.log(localStorage);
3、localStorage 的注意事項(xiàng)
- localStorage 的存儲(chǔ)期限
- localStorage :是持久化的本地存儲(chǔ),除非手動(dòng)清除(比如通過(guò) js 刪除,或者清除瀏覽器緩存),否則數(shù)據(jù)是永遠(yuǎn)不會(huì)過(guò)期的
- sessionStorage:當(dāng)會(huì)話結(jié)束(比如關(guān)閉瀏覽器)的時(shí)候,sessionStorage 中的數(shù)據(jù)會(huì)被清空
- localStorage 鍵和值的類型
- localStorage 存儲(chǔ)的鍵和值只能是字符串類型
- 不是字符串類型,也會(huì)先轉(zhuǎn)化成字符串類型再存進(jìn)去
// localStorage.setItem('students', [{},{}]); console.log( typeof localStorage.getItem('[object Object]'), localStorage.getItem('[object Object]') ); console.log({}.toString()); - 不同域名下能共用 localStorage
- localStorage 的兼容性 :IE7及以下版本不支持 localStorage,IE8 開(kāi)始支持