cookie.js 1.2 KB
Newer Older
徐立's avatar
徐立 committed
1 2 3 4 5 6
/**
 * 设置cookie
 * @param name cookie的名称
 * @param value cookie的值
 * @param day cookie的过期时间
 */
7
export const setCookie = function(name, value, day) {
钟是志's avatar
钟是志 committed
8 9 10 11
  if (day !== 0) {
    //当设置的时间等于0时,不设置expires属性,cookie在浏览器关闭后删除
    const expires = day * 24 * 60 * 60 * 1000;
    const date = new Date(+new Date() + expires);
钟是志's avatar
钟是志 committed
12 13 14 15 16
    let v = value;
    if (name !== 'token') {
      v = escape(v);
    }
    let c = name + '=' + v + ';expires=' + date.toUTCString() + ';path=/';
钟是志's avatar
钟是志 committed
17 18
    // console.log(c);
    document.cookie = c;
钟是志's avatar
钟是志 committed
19
  } else {
钟是志's avatar
钟是志 committed
20
    document.cookie = name + '=' + v + ';path=/';
钟是志's avatar
钟是志 committed
21
  }
徐立's avatar
徐立 committed
22 23 24 25 26 27 28
};

/**
 * 获取对应名称的cookie
 * @param name cookie的名称
 * @returns {null} 不存在时,返回null
 */
29
export const getCookie = function(name) {
钟是志's avatar
钟是志 committed
30 31 32
  let arr;
  const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)');
  arr = document.cookie.match(reg);
钟是志's avatar
钟是志 committed
33 34 35 36 37 38 39
  if (!!arr) {
    if (name === 'token') {
      return arr[2];
    }else{
      return unescape(arr[2]);
    }
  } else return null;
徐立's avatar
徐立 committed
40 41 42 43 44 45
};

/**
 * 删除cookie
 * @param name cookie的名称
 */
46
export const delCookie = function(name) {
钟是志's avatar
钟是志 committed
47
  setCookie(name, '', -1);
徐立's avatar
徐立 committed
48
};