自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

使用原生cookieStore方法,讓Cookie操作更簡(jiǎn)單

開發(fā) 前端
cookieStore?提供的方法比起直接操作document.cookie要簡(jiǎn)便許多,不僅支持增刪改查,還支持通過change事件來監(jiān)聽cookie的變化,但是在使用過程需要注意兼容性問題。

前言

對(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的變化,但是在使用過程需要注意兼容性問題。

責(zé)任編輯:武曉燕 來源: 前端南玖
相關(guān)推薦

2019-04-04 14:05:20

consolejs前端

2009-07-24 17:54:20

iBatis配置

2009-07-21 08:36:59

2011-05-07 16:13:14

數(shù)碼復(fù)合機(jī)

2012-06-20 13:36:42

Surface平板

2022-04-14 07:51:39

TektonTaskRun

2020-06-01 07:41:52

Gmail郵箱郵件安全電子郵件

2019-07-10 10:20:36

前端用戶體驗(yàn)javascript

2015-05-20 12:50:42

C#開發(fā)抽象增刪改

2021-07-24 13:16:31

Android 代碼操作系統(tǒng)

2020-06-16 13:22:22

AI創(chuàng)新深度學(xué)習(xí)

2010-03-23 09:54:35

好壓壓縮

2020-05-07 10:18:06

JavaScript前端技術(shù)

2024-04-26 07:54:07

ZustandReact狀態(tài)管理庫

2022-06-05 23:28:50

TypeScripinfer類型

2009-06-18 15:51:52

SSL VPN負(fù)載均衡Array

2012-09-25 09:28:36

程序員代碼代碼整潔

2015-08-18 11:26:31

DockerExec應(yīng)用容器

2019-07-05 10:45:04

思科魏松斌人工智能
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)