使用原生cookieStore方法,讓Cookie操作更簡(jiǎn)單
前言
對(duì)于前端來講,我們?cè)诓僮鱟ookie時(shí)往往都是基于document.cookie,但它有一個(gè)缺點(diǎn)就是操作復(fù)雜,它并沒有像localStorage那樣提供一些get或set等方法供我們使用。對(duì)與cookie的操作一切都是基于字符串來進(jìn)行的。為了讓cookie的操作更簡(jiǎn)便, Chrome87率先引入了cookieStore方法。
document.cookie
document.cookie可以獲取并設(shè)置當(dāng)前文檔關(guān)聯(lián)的cookie
獲取cookie
const cookie = document.cookie
在上面的代碼中,cookie 被賦值為一個(gè)字符串,該字符串包含所有的 Cookie,每條 cookie 以"分號(hào)和空格 (; )"分隔 (即, key=value 鍵值對(duì))。
圖片
但這拿到的是一整個(gè)字符串,如果你想獲取cookie中的某一個(gè)字段,還需要自己處理
const converter = {
read: function (value) {
if (value[0] === '"') {
value = value.slice(1, -1);
}
return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent)
},
write: function (value) {
return encodeURIComponent(value).replace(
/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,
decodeURIComponent
)
}
}
function getCookie (key) {
const cookies = document.cookie ? document.cookie.split('; ') : [];
const jar = {};
for (let i = 0; i < cookies.length; i++) {
const parts = cookies[i].split('=');
const value = parts.slice(1).join('=');
try {
const foundKey = decodeURIComponent(parts[0]);
jar[foundKey] = converter.read(value, foundKey);
if (key === foundKey) {
break
}
} catch (e) {}
}
return key ? jar[key] : jar
}
console.log(getCookie('name')) // 前端南玖
比如上面這段代碼就是用來獲取單個(gè)cookie值的
設(shè)置cookie
document.cookie = `name=前端南玖;`
它的值是一個(gè)鍵值對(duì)形式的字符串。需要注意的是,用這個(gè)方法一次只能對(duì)一個(gè) cookie 進(jìn)行設(shè)置或更新。
比如:
document.cookie = `age=18; city=shanghai;`
這樣只有age能夠設(shè)置成功
- 以下可選的 cookie 屬性值可以跟在鍵值對(duì)后,用來具體化對(duì) cookie 的設(shè)定/更新,使用分號(hào)以作分隔:
這個(gè)值的格式參見Date.toUTCString() (en-US)
;path=path (例如 '/', '/mydir') 如果沒有定義,默認(rèn)為當(dāng)前文檔位置的路徑。
;domain=domain (例如 'example.com', 'subdomain.example.com') 如果沒有定義,默認(rèn)為當(dāng)前文檔位置的路徑的域名部分。與早期規(guī)范相反的是,在域名前面加 . 符將會(huì)被忽視,因?yàn)闉g覽器也許會(huì)拒絕設(shè)置這樣的 cookie。如果指定了一個(gè)域,那么子域也包含在內(nèi)。
;max-age=max-age-in-seconds (例如一年為 606024*365)
;expires=date-in-GMTString-format
如果沒有定義,cookie 會(huì)在對(duì)話結(jié)束時(shí)過期
;secure (cookie 只通過 https 協(xié)議傳輸)
- cookie 的值字符串可以用encodeURIComponent() (en-US)來保證它不包含任何逗號(hào)、分號(hào)或空格 (cookie 值中禁止使用這些值).
function assign (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
target[key] = source[key];
}
}
return target
}
function setCookie (key, value, attributes) {
if (typeof document === 'undefined') {
return
}
attributes = assign({}, { path: '/' }, attributes);
if (typeof attributes.expires === 'number') {
attributes.expires = new Date(Date.now() + attributes.expires * 864e5);
}
if (attributes.expires) {
attributes.expires = attributes.expires.toUTCString();
}
key = encodeURIComponent(key)
.replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent)
.replace(/[()]/g, escape);
var stringifiedAttributes = '';
for (var attributeName in attributes) {
if (!attributes[attributeName]) {
continue
}
stringifiedAttributes += '; ' + attributeName;
if (attributes[attributeName] === true) {
continue
}
stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
}
return (document.cookie =
key + '=' + converter.write(value, key) + stringifiedAttributes)
}
setCookie('course', 'fe', { expires: 365 })
這里是js-cookie庫對(duì)setCookie方法的封裝
刪除cookie
function removeCookie (key, attributes) {
setCookie(
key,
'',
assign({}, attributes, {
expires: -1
})
);
}
removeCookie('course')
新方法cookieStore
以上就是通過document.cookie來操作cookie的方法,未封裝方法之前操作起來都非常的不方便?,F(xiàn)在我們?cè)賮砹私庖幌滦路椒╟ookieStore,它是一個(gè)類似localStorage的全局對(duì)象。
圖片
它提供了一些方法可以讓我們更加方便的操作cookie
獲取單個(gè)cookie
cookieStore.get(name)
該方法可以獲取對(duì)應(yīng)key的單個(gè)cookie,并且以promise形式返回對(duì)應(yīng)的值
async function getCookie (key) {
const name = await cookieStore.get(key)
console.log('【name】', name)
}
getCookie('name')
圖片
當(dāng)獲取的cookie不存在時(shí),則會(huì)返回null
獲取所有cookie
cookieStore.getAll()
該方法可以獲取所有匹配的cookie,并且以promise形式返回一個(gè)列表
async function getAllCookies () {
const cookies = await cookieStore.getAll()
console.log('【cookies】', cookies)
}
getAllCookies()
當(dāng)cookie不存在時(shí),則會(huì)返回一個(gè)空數(shù)組
設(shè)置cookie
cookieStore.set()
該方法可以設(shè)置cookie,并且會(huì)返回一個(gè)promise狀態(tài),表示是否設(shè)置成功
function setCookie (key, value) {
cookieStore.set(key, value).then(res => {
console.log('設(shè)置成功')
}).catch(err => {
console.log('設(shè)置失敗')
})
}
setCookie('site', 'https://bettersong.github.io/nanjiu/')
如果想要設(shè)置更多的屬性,比如:過期時(shí)間、路徑、域名等,可以傳入一個(gè)對(duì)象
function setCookie (key, value) {
cookieStore.set({
name: key,
value: value,
path: '/',
expires: new Date(2024, 2, 1)
}).then(res => {
console.log('設(shè)置成功')
}).catch(err => {
console.log('設(shè)置失敗')
})
}
setCookie('site', 'https://bettersong.github.io/nanjiu/')
刪除cookie
cookieStore.delete(name)
該方法可以用來刪除指定的cookie,同樣會(huì)返回一個(gè)promise狀態(tài),來表示是否刪除成功
function removeCookie (key) {
cookieStore.delete(key).then(res => {
console.log('刪除成功')
}).catch(err => {
console.log('刪除失敗')
})
}
removeCookie('site')
需要注意的是:即使刪除一個(gè)不存在的cookie也會(huì)返回刪除成功狀態(tài)
監(jiān)聽cookie
cookieStore.addEventListener('change', (event) => {
console.log(event)
});
可以通過change事件來監(jiān)聽cookie的變化,無論是通過cookieStore操作的,還是通過document.cookie來操作的都能夠監(jiān)聽到。
該方法的返回值有兩個(gè)字段比較重要,分別是:change盒delete,它們都是數(shù)組類型。用來存放改變和刪除的cookie信息
監(jiān)聽修改
調(diào)用set方法時(shí),會(huì)觸發(fā)change事件,修改或設(shè)置的cookie會(huì)存放在change數(shù)組中
cookieStore.addEventListener('change', (event) => {
const type = event.changed.length ? 'change' : 'delete';
const data = (event.changed.length ? event.changed : event.deleted).map((item) => item.name);
console.log(`【${type}】, cookie:${JSON.stringify(data)}`);
});
function setCookie (key, value) {
cookieStore.set(key, value).then(res => {
console.log('設(shè)置成功')
}).catch(err => {
console.log('設(shè)置失敗')
})
}
setCookie('site', 'https://bettersong.github.io/nanjiu/')
??需要注意的是:
- 通過document.cookie設(shè)置或刪除cookie時(shí),都是會(huì)觸發(fā)change事件,不會(huì)觸發(fā)delete事件
- 即使兩次設(shè)置cookie的name和value都相同,也會(huì)觸發(fā)change事件
監(jiān)聽刪除
調(diào)用delete方法時(shí),會(huì)觸發(fā)change事件,刪除的cookie會(huì)存放在delete數(shù)組中
cookieStore.addEventListener('change', (event) => {
const type = event.changed.length ? 'change' : 'delete';
const data = (event.changed.length ? event.changed : event.deleted).map((item) => item.name);
console.log(`【${type}】, cookie:${JSON.stringify(data)}`);
});
function removeCookie (key) {
cookieStore.delete(key).then(res => {
console.log('刪除成功')
}).catch(err => {
console.log('刪除失敗')
})
}
removeCookie('site')
??需要注意的是:
- 如果刪除一個(gè)不存在的cookie,則不會(huì)觸發(fā)change事件
兼容性
在使用該方法時(shí)需要注意瀏覽器的兼容性
總結(jié)
cookieStore提供的方法比起直接操作document.cookie要簡(jiǎn)便許多,不僅支持增刪改查,還支持通過change事件來監(jiān)聽cookie的變化,但是在使用過程需要注意兼容性問題。