Skip to content

Cookie Getter and Setter 封装 #16

@hexson

Description

@hexson

昨晚利用十多分钟空闲时间造了一个小轮子,不依赖任何库的 Cookie Getter and Setter 封装,并且兼容 AMD / CMD 模块化标准。

源码

/**
 * Gets or sets cookies @hexson
 * @param cookie's name
 * @param cookie's value
 * @param options{domain, expires, path}, expires(in days)
 * @return true or false or value
 */


;(function(){
  "use strict";

  var HoCookie = {
    trim: function (string) {
      return string.replace(/(^\s*)|(\s*$)/g, "");
    },
    get: function (name) {
      var n, v, cookies = document.cookie.split(";");
      for (var i = 0; i < cookies.length; i++) {
        n = this.trim(cookies[i].substr(0, cookies[i].indexOf("=")));
        v = cookies[i].substr(cookies[i].indexOf("=") + 1);
        if (n === name) {
          return unescape(v);
        }
      }
    },
    set: function (name, value, options) {
      options = options || {};
      if (!value) {
        value = "";
        options.expires = -365;
      } else {
        value = escape(value);
      }
      if (options.expires) {
        var d = new Date();
        d.setDate(d.getDate() + options.expires);
        value += "; expires=" + d.toGMTString();
      }
      value += options.domain ? ("; domain=" + options.domain) : "";
      value += options.path ? ("; path=" + options.path) : "";
      document.cookie = name + "=" + value;
      if (this.get(name) === value) return true;
      else return false;
    },
    mix: function (name, value, options) {
      if (typeof value === "undefined") this.get(name);
      else this.set(name, value, options);
    }
  };

  window.HoCookie = HoCookie;
})();
/*
 *=============================*
 *     HoCookie AMD Export     *
 *=============================*
 */
if (typeof module !== "undefined" && typeof exports === "object" && define.cmd) {
  module.exports = window.HoCookie;
} else if (typeof define === "function" && define.amd) {
  define([], function () {
    "use strict";
    return window.HoCookie;
  });
}

实例

新建一个 hocookie.js 文件储存在网站根目录下 lib 的文件夹中,复制上面的源码,粘贴进之前新建的 hocookie.js 文件中,在 <body>...</body> 后引入:

<script type="text/javascript" src="/lib/hocookie.js"></script>

引入后即可在你之后的 javascript 代码中使用:

window.onload = function () {
  var getCookieValue;

  // 设置 cookie
  HoCookie.set("test", "520", { expires: 7, path: "/" });

  // 读取 cookie
  getCookieValue = HoCookie.get("test");
  console.log(getCookieValue);  // 520

  // 删除 cookie
  HoCookie.set("test", null);

  getCookieValue = HoCookie.get("test");
  console.log(getCookieValue);  // null

  // 设置和读取 cookie 的混合方法
  HoCookie.mix("test", "520", { expires: 7, path: "/" });  // 设置
  getCookieValue = HoCookie.mix("test");  // 读取
  console.log(getCookieValue);  // 520
  HoCookie.mix("test", null);  // 删除

  getCookieValue = HoCookie.mix("test");
  console.log(getCookieValue);  // null
};

参数

get

name 接收一个参数,即要读取的 cookie 的名称

set

name 要设置的 cookie 的名称

value 要设置的 cookie 的值

options 一个对象,可选,包含 { expires: "cookie有效期(天)", path: "cookie储存的路径", domain: "cookie储存的域名(站点)"}

mix

综合方法,传一个参数见 get,传两个以上参数见 set

欢迎使用。

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions