js 原生方法操做 cookie 詳解

js 原生方法操做 cookie 詳解

客戶端存儲小型數據的方式有 cookiestorage 兩種
這兩種存儲方式都是基於站點的,也就是說不一樣的站點有不一樣的cookiestoragejquery

cookie
document 的屬性,也就是 window.document.cookie
用於存儲小的數據,如 username email uuid token等,並能夠設置數據的過時時間

storage
window 的屬性,也就是 window.localStorage
能夠永久存儲數據,並能夠用於存儲相對大一些的數據,通常認爲能夠存儲幾M大小的數據chrome

本文介紹 cookie 的經常使用方法瀏覽器

cookie 是個什麼東西

cookie 本質其實就是個字符串,好比,看一下 https://so.com 的 cookie 是這樣的cookie

cookie-string.png

也能夠經過瀏覽器調試窗口查看,如 chrome 去 application-> cookie 中查看session

application-cookie.png

原生 cookie 使用

既然上面看到 cookie 實際上是個字符串,就能夠寫個讀取價值對的方法,在用的時候直接返回鍵值對。更簡單的,能夠直接使用 jquery.cookie.js 對應的使用方法能夠百度,這裏再也不細說。app

這裏說一下比較細節的地方,關於設置 cookie 時的一些參數:dom

參數名 說明 例子 可選參數
path 默認是當前文檔的目錄 /
domain cookie 做用域名,不一樣域名會有不一樣的 cookie kylebing.cn
max-age 秒爲單位,最大存活時長 60
expires 存活截止時間。Date.toUTCString() 形式的時間格式。 若是 max-age 和 expires 都沒有設置,這個 cookie 就是 session 類型的,關閉當前窗口就刪掉了 Mon, 16 Dec 2019 01:45:15 GMT
secure 經過 https 傳輸
samesite 這塊還不太瞭解 strictlax

設置 cookie

原生設置 cookie 是這樣的測試

document.cookie ='新 cookie 字符串'
document.cookie = "name=Kyle;path=/;domain=kylebing.cn;max-age=60;secure=https;samesite=strict"

console.png

讀取 cookie

1. 讀取 cookie 字符串

讀取 cookie,是直接把整個 cookie 字段拿到,再拆開字符串ui

let cookieString = document.cookie

// diaryEmail=kylebing%40163.com; diaryUsername=%E5%8D%81%E6%9C%88; diaryUid=3; diaryCategories=%5B%22life%22%2C%22study%22%2C%22work%22%2C%22sport%22%2C%22game%22%2C%22film%22%2C%22bigevent%22%2C%22other%22%5D; diaryToken=123456789123456789;

2. 拆分鍵值字符串

先觀察這個字符串的規律,每一個鍵值對是以 ; 分隔的,名字和值之間以 = 分隔。
這些鍵值對之間除了 ; 以外還有一個空格,只能最後一個是單獨的 ;spa

因此咱們要作的就是先把最後面的 ; 去掉,而後再拆分整個字符串

let cookie = 'diaryEmail=kylebing%40163.com; diaryUsername=%E5%8D%81%E6%9C%88; diaryUid=3; diaryCategories=%5B%22life%22%2C%22study%22%2C%22work%22%2C%22sport%22%2C%22game%22%2C%22film%22%2C%22bigevent%22%2C%22other%22%5D; diaryToken=123456789123456789;';
cookie = cookie.substring(0, cookie.length - 1); // 去掉最後的 `;` 號
let tempCookieArray =  cookie.split('; '); // 拆分字符串

cookie-array.png

3. 分離出字符串中的鍵和值

遍歷前面拆分開的字符串,取 = 先後的內容,前面是名,後面是值

tempCookieArray.forEach(item => {
    let name = item.substring(0, item.indexOf('='));
    let value = item.substring(item.indexOf('=') + 1);
    console.log(`${name}: ${value}`);
});

輸出以下:

key-value.png

4. 轉義字符串

此時發現一個問題,就是值裏若是有漢字什麼的,它顯示的是被處理的字符串,咱們須要把它還原回來。

這裏先作一個測試,咱們能夠經過 decodeURIComponent() 這個方法還原字符串

這個方法相對的方法是下面這個,看名字就知道什麼意思了,目的是轉成能夠在地址欄中顯示的字符

  • encodeURIComponent()
  • decodeURIComponent()

escape.png

有了以上的知識,咱們就能夠還原 cookie 中的內容了

value = decodeURIComponent(value)

5. 放入對象中

取得鍵名和值以後,咱們須要把這兩個值封裝成對象,好在後面用的時候方便。

let cookieObject = {}; // 存放 cookie 鍵值對

tempCookieArray.forEach(item => {
    let name = item.substring(0, item.indexOf('='));
    let value = item.substring(item.indexOf('=') + 1);
    value = decodeURIComponent(value); // 還原字符串
    cookieObject[name] = value; // 將鍵值插入中這個對象中
});

console.log(cookieObject);

結果以下:

cookie-object.png

6. 封裝成方法

爲了之後方便使用,能夠直接封裝成方法

/**
 * 獲取 cookie 對象
 * @returns  cookie 鍵值對對象
 */
function getCookieObject() {
    let cookieString = document.cookie;
    cookieString = cookieString.substring(0, cookieString.length - 1);
    let tempCookieArray = cookieString.split('; ');

    let cookieObject = {}; // 存放 cookie 鍵值對

    tempCookieArray.forEach(item => {
        let name = item.substring(0, item.indexOf('='));
        let value = item.substring(item.indexOf('=') + 1);
        value = decodeURIComponent(value); // 還原字符串
        cookieObject[name] = value; // 將鍵值插入中這個對象中
    });

    return cookieObject // 返回包含 cookie 鍵值對的對象
}

changeto-lib.png

相關文章
相關標籤/搜索