DIV CSS 佈局教程網

JavaScript 操作 Cookie 的完整方法整理
編輯:JavaScript綜合知識     

Cookie 是在瀏覽器端保存少量資料的經典手段,常用於記住登入狀態、使用者偏好等。本文整理了一整套操作 Cookie 的方法,涵蓋設定、讀取、刪除,以及判斷是否存在、依名稱或值查詢、格式化輸出等進階用法。

設定、刪除與清空 Cookie

SetCookie 用來寫入,其中的 expires 是以「天數」計算;DeleteCookie 透過把過期時間設為過去來刪除單一 Cookie;DelAllCookies 則一次清空所有 Cookie。所有名稱與值都會經過 encodeURIComponent 編碼,避免特殊字元出問題。

// 設定 Cookie(expires 為天數)
var SetCookie = function (name, value, expires, path, domain, secure) {
  var expires_date;
  if (expires) {
    expires_date = new Date();
    expires_date.setDate(expires_date.getDate() + expires);
  }
  document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) +
    ((expires) ? ";expires=" + expires_date.toUTCString() : "") +
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ((secure) ? ";secure" : "");
};

// 刪除單一 Cookie
var DeleteCookie = function (name, path, domain) {
  document.cookie = encodeURIComponent(name) + "=" +
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ";expires=Fri, 01-Jan-2010 00:00:01 UTC";
};

// 清空所有 Cookie
var DelAllCookies = function () {
  var currDate = new Date(), i, theCookie = document.cookie.split(";");
  currDate = currDate.toUTCString();
  i = theCookie.length;
  while (i--) {
    document.cookie = theCookie[i] + "; expires =" + currDate;
  }
};

輔助函式與查詢方法

EscapeReg 負責把字串轉義成正則表達式可用的形式。接著四個查詢函式皆為「不分大小寫」:CNameExists 判斷名稱是否存在、CValueExists 判斷值是否存在、CNameGet 依值反查名稱、CValueGet 依名稱取值;最後 CookieStr 會把所有 Cookie 格式化成一行一筆的文字,方便放進 textarea 檢視。

var EscapeReg = function (str) {
  return str.replace(/[-[]{}()*+?.,^$|#\s]/g, "$&");
};

// 判斷名稱是否存在(不分大小寫)
var CNameExists = function (cookie_name) {
  var testName, myReg;
  if (document.cookie.length == 0) return false;
  testName = EscapeReg(cookie_name);
  myReg = new RegExp('(^|;) ?' + testName + '=([^;]*)(;|$)', 'i');
  return myReg.test(decodeURIComponent(document.cookie));
};

// 判斷值是否存在(不分大小寫)
var CValueExists = function (cookie_value) {
  var testName, myReg;
  if (document.cookie.length == 0) return false;
  testName = EscapeReg(cookie_value);
  myReg = new RegExp('(=)' + testName + '(;|$)', 'i');
  return myReg.test(decodeURIComponent(document.cookie));
};

// 依值反查名稱(不分大小寫)
var CNameGet = function (cookie_value) {
  var testName, myReg, results;
  if (document.cookie.length == 0) return '';
  testName = EscapeReg(cookie_value);
  myReg = new RegExp('(^|;) ?([^=]*)=' + testName + '(;|$)', 'i');
  results = decodeURIComponent(document.cookie).match(myReg);
  return (results) ? results[2] : '';
};

// 依名稱取值(不分大小寫)
var CValueGet = function (cookie_name) {
  var testName, myReg, results;
  if (document.cookie.length == 0) return '';
  testName = EscapeReg(cookie_name);
  myReg = new RegExp('(^|;) ?' + testName + '=([^;]*)(;|$)', 'i');
  results = decodeURIComponent(document.cookie).match(myReg);
  return (results) ? results[2] : '';
};

// 回傳格式化後的所有 Cookie 字串
var CookieStr = function () {
  return decodeURIComponent(document.cookie).
    replace(/([^=;]+)=([^;]*)[;\s]*/g, '$1 ($2)\n') || '';
};

使用提醒

要特別注意的是,這些查詢函式本身不會自動去除名稱或值的空白,呼叫端最好先自行 trim;另外,Cookie 有大小限制(一般單域名稱約 4KB),且不宜存放敏感資訊,真正的敏感資料仍應放在後端並以安全機制保護。希望這份 Cookie 操作整理對大家的 JavaScript 開發有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved