超詳細的Cookie增刪改查
1,什麼是 Cookie?
Cookie是一些數據, 存儲於你電腦上的文本文件中。
當web伺服器向瀏覽器發送web頁面時,在連接關閉後,服務端不會記錄用戶的資訊。Cookie的作用就是用於解決如何記錄客戶端的用戶資訊。當用戶訪問web頁面時,他的名字可以記錄在Cookie中。在該用戶下一次訪問該頁面時,可以在Cookie中讀取該用戶的訪問記錄。
- 當瀏覽器從伺服器上請求
web頁面時, 屬於該頁面的Cookie會被添加到該請求中。服務端可以通過這種方式來獲取用戶的資訊。
1.1,存儲形式
Cookie以鍵值對形式存儲,如下所示:
userName=pony
1.2,常用屬性
| 屬性 | 用處 | 默認值 |
|---|---|---|
| Name | 鍵 | 無 |
| Value | 值 | 無 |
| Domain | 允許訪問的域 | 當前域 |
| Path | 允許訪問的路徑 | 當前路徑 |
| Expires / Max-Age | 過期時間 | 關閉頁面即清除(Session) |
| Size | 佔用位元組大小 | 無需設置 |

1.3,大小限制
| 瀏覽器 | 大小 (KB) | 每個域存儲個數限制 |
|---|---|---|
| Firefox | 4 | 無 |
| Safari | 4 | 無 |
| Opera | 4 | 30 |
| IE | 4 | 50 |
| Edge | 4 | 50 |
| Chrome | 4 | 50 |
2,增 or 改Cookie
/**
* 設置cookie
* @param {String} key 鍵
* @param {String} value 值
* @param {String} expires 過期時間(yyyy-MM-dd 或 yyyy-MM-dd HH:mm:ss 或 時間戳) => default:頁面關閉即過期(Session)
* @param {String} domain 域 => default:當前域
* @param {String} path 路徑 => default:/
*/
function setCookie(key, value, expires = '', domain = window.location.hostname, path = '/') {
const time = expires ? new Date(expires) : expires
console.log(time)
const cookie = `${key}=${value}; expires=${time}; domain=${domain}; path=${path}`
document.cookie = cookie
}
調用例子:
setCookie('user', '我是你爸爸', '2022-02-20 16:29:00').
// 或者
setCookie('user', '我是你爸爸', '2022-02-20')
// 或者
const timestamp = new Date('2022-10-01').getTime()
setCookie('user', '我是你爸爸', timestamp)
3,查Cookie
/**
* 獲取所有cookie的key
* @return {Array<string>} Cookie鍵組成的數組
*/
function getAllCookieKey() {
const Cookie = document.cookie
const cookieList = Cookie.split('; ')
return cookieKeyList = cookieList.map(item => {
return item.split('=')[0]
})
}
/**
* 根據cookie的key獲取對應的值
* @param {String} key 鍵
* @return {String} value 值
*/
function cookieKeyGetValue(key) {
const Cookie = document.cookie
const cookieList = Cookie.split('; ')
const cookieKeyList = cookieList.map(item => {
return item.split('=')[0]
})
const index = cookieKeyList.indexOf(key)
return cookieList[index].split('=')[1]
}
4,刪Cookie
/**
* 根據key清除cookie
* @param {String} key 鍵
* @param {String} domain 域 => default:當前域
* @param {String} path 路徑 => default:/
*/
function clearCookie(key, domain = window.location.hostname, path = '/') {
const Time = new Date()
Time.setTime(Time.getTime() + -1 * 24 * 60 * 60 * 1000)
const expires = `expires=${Time.toUTCString()}`
document.cookie = `${key}=; ${expires}; path=${path}; domain=${domain}`
}
// 清除所有cookie
function clearAllCookie() {
const cookieKeyList = getAllCookieKey()
for (let key of cookieKeyList) {
clearCookie(key)
}
}
如果看了覺得有幫助的,我是@鵬多多,歡迎 點贊 關注 評論;END
PS:在本頁按F12,在console中輸入document.querySelectorAll(‘.diggit’)[0].click(),有驚喜哦
公眾號
往期文章
- 助你上手Vue3全家桶之Vue-Router4教程
- 助你上手Vue3全家桶之Vue3教程
- 助你上手Vue3全家桶之VueX4教程
- 使用nvm管理node.js版本以及更換npm淘寶鏡像源
- 超詳細!Vue-Router手把手教程
- vue中利用.env文件存儲全局環境變數,以及配置vue啟動和打包命令
- 微信小程式實現搜索關鍵詞高亮
- 超詳細!Vue的九種通訊方式
- 超詳細!Vuex手把手教程
個人主頁



