🍪

任意のcookieを設定、取得する関数

2023/01/31に公開約2,100字

任意のcookieを設定・取得する関数です
この例ではtimeObjの値をmax-ageに反映させます

setCookie()の第一引数にcookie名、第二にcookieの中身、第三にmax-age(秒)を任意に設定します

const timeObj = {
  sec: 10, //秒
  min: 0, //分
  hour: 0, //時
  day: 0 //日
}

const date = new Date();

//set cookie name
const cookieName = "stopLoadingAnimation";

//set finished time
const finishedTime = setFinishTime(date.getTime() + additionTime(timeObj));

//set max-age
const maxAge = additionTime(timeObj, false);

//set arbitrary cookie
setCookie(cookieName, finishedTime, maxAge);

/**
 * return finish time
 * @param {*} timestamp 
 * @returns 
 */
function setFinishTime(timestamp) {
  let date = new Date(timestamp);
  let options = { weekday: 'short', year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' };
  return date.toLocaleDateString('ja-JP', options);
}

/**
 * return addition time in milliseconds or seconds
 * @param {*} obj time obj
 * @param {*} isMillisecond 
 * @returns 
 */
function additionTime(obj, isMillisecond = true) {
  const Min = obj.min * 60;
  const Hour = obj.hour * 60 * 60;
  const Day = obj.day * 24 * 60 * 60;
  const Time = obj.sec + Min + Hour + Day;

  //when you want to use milliseconds for calculations
  if (isMillisecond) {
    return Time * 1000;
  } //when you want to set true time
  else {
    return Time;
  }
}

/**
 * set an arbitrary cookie
 * @param {*} cookieName cookie name
 * @param {*} cookieValue cookie value
 * @param {*} cookieAge max-age
 */
function setCookie(cookieName, cookieValue, cookieAge) {
  document.cookie = `${cookieName}=${cookieValue}; max-age=${cookieAge}`;
}

/**
 * get a specific cookie
 * @param {*} cookieName 設定するcookieの名前
 * @returns 
 */
function getCookieValue(cookieName) {
  const cookieNameLen = cookieName.length
  const allCookies = document.cookie;
  const cookieIdx = allCookies.indexOf(`${cookieName}=`);

  //cookieが見つからない場合はnullを返す
  if (cookieIdx == -1) return null;

  if (cookieIdx != -1) {
    const start = cookieIdx + cookieNameLen + 1;
    let end = allCookies.indexOf(";", start);
    if (end == -1) end = allCookies.length;
    let value = allCookies.substring(start, end);
    return value;
  }
}

Discussion

ログインするとコメントできます