DIV CSS 佈局教程網

JavaScript Cookie 操作封裝:類別版與函數版兩種實作
編輯:關於JavaScript     

Cookie 是前端最早的持久化手段,直到今天仍在使用(認證 token、主題偏好、A/B 測試分組等)。原生 API 只有 document.cookie 一個字串入口,讀寫都得自己解析,因此實務上幾乎都會做一層封裝。以下提供兩種風格。

第一種:物件導向封裝

String.prototype.Trim = function () {
  return this.replace(/^\s+/g, "").replace(/\s+$/g, "");
};

function JSCookie() {

  // 讀取整個 cookie
  this.GetCookie = function (key) {
    var cookie = document.cookie;
    var cookieArray = cookie.split(';');
    var getvalue = "";
    for (var i = 0; i < cookieArray.length; i++) {
      if (cookieArray[i].Trim().substr(0, key.length) == key) {
        getvalue = cookieArray[i].Trim().substr(key.length + 1);
        break;
      }
    }
    return getvalue;
  };

  // 讀取子鍵,例如 key4 存的是 "k1=1&k2=2&k3=3"
  this.GetChild = function (cookiekey, childkey) {
    var child = this.GetCookie(cookiekey);
    var childs = child.split('&');
    var getvalue = "";
    for (var i = 0; i < childs.length; i++) {
      if (childs[i].Trim().substr(0, childkey.length) == childkey) {
        getvalue = childs[i].Trim().substr(childkey.length + 1);
        break;
      }
    }
    return getvalue;
  };

  // 寫入
  this.SetCookie = function (key, value, expire, domain, path) {
    var cookie = "";
    if (key != null && value != null) cookie += key + "=" + value + ";";
    if (expire != null) cookie += "expires=" + expire.toGMTString() + ";";
    if (domain != null) cookie += "domain=" + domain + ";";
    if (path   != null) cookie += "path="   + path   + ";";
    document.cookie = cookie;
  };

  // 刪除:把過期時間設到過去
  this.Expire = function (key) {
    var expire_time = new Date();
    expire_time.setFullYear(expire_time.getFullYear() - 1);
    document.cookie = " " + key + "=e;expires=" + expire_time + ";";
  };
}

使用方式

var cookie = new JSCookie();

// 一、設定
cookie.SetCookie("key1", "val1");                       // 一般設定

var expire_time = new Date();
expire_time.setFullYear(expire_time.getFullYear() + 1);
cookie.SetCookie("key2", "val2", expire_time);           // 有效期限一年

cookie.SetCookie("key3", "val3", expire_time, ".cnblogs.com", "/");  // 指定網域與路徑

cookie.SetCookie("key4", "k1=1&k2=2&k3=3");            // 帶子鍵

// 二、讀取
cookie.GetCookie("key1");
cookie.GetChild("key4", "k1");                            // 取子鍵 k1

// 三、刪除
cookie.Expire("key1");

第二種:函數式封裝

function setCookie(name, value, days) {
  var argv = setCookie.arguments;
  var argc = argv.length;
  var expires = (argc > 2) ? argv[2] : null;

  var LargeExpDate = null;
  if (expires != null) {
    LargeExpDate = new Date();
    LargeExpDate.setTime(LargeExpDate.getTime() + (expires * 1000 * 3600 * 24));
  }

  document.cookie = name + "=" + escape(value)
                  + ((expires == null) ? "" : ("; expires=" + LargeExpDate.toGMTString()));
}

function getCookie(Name) {
  var search = Name + "=";
  if (document.cookie.length > 0) {
    var offset = document.cookie.indexOf(search);
    if (offset != -1) {
      offset += search.length;
      var end = document.cookie.indexOf(";", offset);
      if (end == -1) end = document.cookie.length;
      return unescape(document.cookie.substring(offset, end));
    }
    return "";
  }
  return "";
}

應用範例:只顯示一次的提示

if (getCookie("yxjok") != "ok") {
  document.write('<div id="jb51_yxj">...</div>');
}

function Closeyxj() {
  $("jb51_yxj").style.display = 'none';
  setCookie("yxjok", "ok", 1);      // 記錄一天
}

若要改成「幾分鐘後再顯示」,只要調整時間單位即可(把 24 小時換算改成乘 300 秒的倍數):

function setADCookie(name, value, minutes) {
  var exp = new Date();
  exp.setTime(exp.getTime() + minutes * 60 * 1000);
  document.cookie = name + "=" + escape(value) + "; expires=" + exp.toGMTString();
}

這兩份程式碼該修正的地方

它們寫於一個特定的年代,有幾處在今天必須調整。

不要擴充 String.prototype。 第一版在 String.prototype 上加了 Trim(而且命名用了大寫開頭,與內建方法風格不一致)。修改內建原型是全域副作用,可能與其他函式庫衝突。ES5 已有原生的 String.prototype.trim(),直接用即可。

escape / unescape 已廢棄。 它們對非 ASCII 字元的處理不正確(中文會被編成 %uXXXX,這不是任何標準的 URI 編碼)。應改用 encodeURIComponent 與 decodeURIComponent。

key 比對不精確。 substr(0, key.length) == key 會讓 key 誤中 key2。應比對 name + "=" 的完整前綴。

toGMTString 已廢棄。 改用 toUTCString(),或直接寫 ISO 格式。

刪除 cookie 時 path 必須一致。 寫入時若指定了 path=/app/,刪除時不指定相同 path 就會失敗——瀏覽器會認為那是另一個 cookie。這是最常見的「刪不掉」原因。

現代寫法

function setCookie(name, value, days) {
  var parts = [encodeURIComponent(name) + '=' + encodeURIComponent(value)];
  if (days) {
    var d = new Date();
    d.setTime(d.getTime() + days * 864e5);
    parts.push('expires=' + d.toUTCString());
  }
  parts.push('path=/');
  document.cookie = parts.join('; ');
}

function getCookie(name) {
  var target = encodeURIComponent(name) + '=';
  var pairs = document.cookie ? document.cookie.split('; ') : [];
  for (var i = 0; i < pairs.length; i++) {
    if (pairs[i].indexOf(target) === 0) {
      return decodeURIComponent(pairs[i].substring(target.length));
    }
  }
  return null;
}

function deleteCookie(name) {
  document.cookie = encodeURIComponent(name) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
}

最後要提醒的是 Cookie 的定位問題。它每次請求都會被動附上,容量只有 4KB 左右,而且內容在使用者端可被讀取與竄改——因此永遠不要把 Cookie 當成信任來源,敏感資料該放在 server 端 session,Cookie 裡只留一個不可猜的識別碼,並加上 HttpOnly(禁止 JS 讀取,降低 XSS 竊取風險)與 Secure(僅經 HTTPS 傳輸)兩個旗標。這兩個屬性前端 JS 無法設定,必須由伺服器端下發,這也說明了為什麼「Cookie 操作」這件事,最終不能只在前端完成。

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