JS Code block 代码块–cookie

星期二, 2023-04-18 | Author: Lee | computer, 前端 | 1,025 views

cookie
获取cookie 里的值
设置cookie
删除cookie

/**
 * 获取cookie 里的值
 * @param {String} key
 */
export const getCookie = (key) => {
  const arr = document.cookie.match(new RegExp(`(^| )${key}=([^;]*)(;|$)`));
  if (arr != null) return unescape(arr[2]);
  return null;
}
 
/**
 * 设置cookie
 * @param name
 * @param value
 * @param day expires的时间
 */
function setCookie (name, value, day) {
    let setting = arguments[0];
    if (Object.prototype.toString.call(setting).slice(8, -1) === 'Object'){
        for (let i in setting) {
            let oDate = new Date();
            oDate.setDate(oDate.getDate() + day);
            document.cookie = i + '=' + setting[i] + ';expires=' + oDate;
        }
    }else{
        let oDate = new Date();
        oDate.setDate(oDate.getDate() + day);
        document.cookie = name + '=' + value + ';expires=' + oDate;
    }
 
}
 
/** 
 * 删除cookie
 */
function removeCookie (name) {
    setCookie(name, 1, -1);
}

Tags:

文章作者: Lee

本文地址: https://www.pomelolee.com/2385.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

No comments yet.

Leave a comment

Search

文章分类

Links

Meta