javascript操作cookie程式碼封裝

admin發表於2017-04-12

對於cookie的操作無非就是設定、獲取或者刪除等操作。

如果將這些操作都封裝在一起,那麼使用起來非常的方便。

程式碼例項如下:

[JavaScript] 純文字檢視 複製程式碼
var CookieUtil = {
  //根據key讀取cookie
  get: function (name) {
    //注意對鍵編碼
    var cookieName = encodeURIComponent(name) + "=",
        cookieStart = document.cookie.indexOf(cookieName),
        cookieValue = null,
        cookieEnd;
    //找到cookie鍵   
    if (cookieStart > -1) {
      //鍵後面第一個分號位置
      cookieEnd = document.cookie.indexOf(";", cookieStart);
      if (cookieEnd == -1) {
        cookieEnd = document.cookie.length;
      }
      //cookie值解碼
      cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
    }
    return cookieValue;
  },
  //設定cookie
  set: function (name, value, expires, path, domain, secure) {
    var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
    //失效時間,GMT時間格式
    if (expires instanceof Date) {
      cookieText += "; expires=" + expires.toGMTString();
    }
    if (path) {
      cookieText += "; path=" + path;
    }
    if (domain) {
      cookieText += "; domain=" + domain;
    }
    if (secure) {
      cookieText += "; secure";
    }
    document.cookie = cookieText;
  },
  //刪除cookie,保持相同的鍵、域、路徑、安全選項,然後設定失效時間即可
  unset: function (name, path, domain, secure) {
    this.set(name, "", new Date(0), path, domain, secure);
  }
};

相關文章