js對cookie操作一些常用功能的封裝程式碼例項

admin發表於2017-04-02

下面是一段對cookie相關操作的封裝程式碼。封裝好形成一個外掛的程式碼總好過於零碎的程式碼,需要的朋友可以做一下參考。

雖然使用方便,最好還是能夠掌握程式碼的例項原理。

程式碼例項如下:

[JavaScript] 純文字檢視 複製程式碼
Angela.cookie = { //# Cookie
  // 瀏覽器是夠支援 cookie
  enable: !!navigator.cookieEnabled
  //讀取COOKIE
  , get: function (name) { //#讀取 cookie
    var reg = new RegExp("(^| )" + name + "(?:=([^;]*))?(;|$)")
      , val = document.cookie.match(reg)
    ;
    return val ? (val[2] ? unescape(val[2]) : "") : '';
  }
  //寫入COOKIES
  , set: function (name, value, expires, path, domain, secure) { //# 寫入 cookie
    var exp = new Date()
      , expires = arguments[2] || null
      , path = arguments[3] || "/"
      , domain = arguments[4] || null
      , secure = arguments[5] || false
    ;
    expires ? exp.setMinutes(exp.getMinutes() + parseInt(expires)) : "";
    document.cookie = name + '=' + escape(value) 
        + (expires ? ';expires=' + exp.toGMTString() : '') 
        + (path ? ';path=' + path : '') 
        + (domain ? ';domain=' + domain : '') + (secure ? ';secure' : '');
  }
  //刪除cookie
  , del: function (name, path, domain, secure) { //#刪除 cookie
    var value = $getCookie(name);
    if (value != null) {
      var exp = new Date();
      exp.setMinutes(exp.getMinutes() - 1000);
      path = path || "/";
      document.cookie = name + '=;expires=' + exp.toGMTString() 
          + (path ? ';path=' + path : '') 
          + (domain ? ';domain=' + domain : '') + (secure ? ';secure' : '');
    }
  }
};

相關文章