對(duì)于前端來(lái)講,我們?cè)诓僮鱟ookie時(shí)往往都是基于document.cookie,但它有一個(gè)缺點(diǎn)就是操作復(fù)雜,它并沒(méi)有像localStorage那樣提供一些get或set等方法供我們使用。對(duì)與cookie的操作一切都是基于字符串來(lái)進(jìn)行的。為了讓cookie的操作更簡(jiǎn)便, Chrome87率先引入了cookieStore方法。
document.cookie可以獲取并設(shè)置當(dāng)前文檔關(guān)聯(lián)的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')) // 前端南玖
比如上面這段代碼就是用來(lái)獲取單個(gè)cookie值的
document.cookie = `name=前端南玖;`
它的值是一個(gè)鍵值對(duì)形式的字符串。需要注意的是,用這個(gè)方法一次只能對(duì)一個(gè) cookie 進(jìn)行設(shè)置或更新。
比如:
document.cookie = `age=18; city=shanghai;`
這樣只有age能夠設(shè)置成功
這個(gè)值的格式參見Date.toUTCString() (en-US)
;path=path (例如 '/', '/mydir') 如果沒(méi)有定義,默認(rèn)為當(dāng)前文檔位置的路徑。
;domain=domain (例如 'example.com', 'subdomain.example.com') 如果沒(méi)有定義,默認(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
如果沒(méi)有定義,cookie 會(huì)在對(duì)話結(jié)束時(shí)過(guò)期
;secure (cookie 只通過(guò) https 協(xié)議傳輸)
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庫(kù)對(duì)setCookie方法的封裝
function removeCookie (key, attributes) { setCookie( key, '', assign({}, attributes, { expires: -1 }) );}removeCookie('course')
以上就是通過(guò)document.cookie來(lái)操作cookie的方法,未封裝方法之前操作起來(lái)都非常的不方便。現(xiàn)在我們?cè)賮?lái)了解一下新方法cookieStore,它是一個(gè)類似localStorage的全局對(duì)象。
圖片
它提供了一些方法可以讓我們更加方便的操作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
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ù)組
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è)置更多的屬性,比如:過(guò)期時(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/')
cookieStore.delete(name)
該方法可以用來(lái)刪除指定的cookie,同樣會(huì)返回一個(gè)promise狀態(tài),來(lái)表示是否刪除成功
function removeCookie (key) { cookieStore.delete(key).then(res => { console.log('刪除成功') }).catch(err => { console.log('刪除失敗') })}removeCookie('site')
需要注意的是:即使刪除一個(gè)不存在的cookie也會(huì)返回刪除成功狀態(tài)
cookieStore.addEventListener('change', (event) => { console.log(event)});
可以通過(guò)change事件來(lái)監(jiān)聽cookie的變化,無(wú)論是通過(guò)cookieStore操作的,還是通過(guò)document.cookie來(lái)操作的都能夠監(jiān)聽到。
該方法的返回值有兩個(gè)字段比較重要,分別是:change盒delete,它們都是數(shù)組類型。用來(lái)存放改變和刪除的cookie信息
調(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/')
??需要注意的是:
調(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')
??需要注意的是:
在使用該方法時(shí)需要注意瀏覽器的兼容性
cookieStore提供的方法比起直接操作document.cookie要簡(jiǎn)便許多,不僅支持增刪改查,還支持通過(guò)change事件來(lái)監(jiān)聽cookie的變化,但是在使用過(guò)程需要注意兼容性問(wèn)題。
本文鏈接:http://www.www897cc.com/showinfo-26-75335-0.html使用原生cookieStore方法,讓Cookie操作更簡(jiǎn)單
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com