JS | 쿠키 활용법

|

요약

쿠키는 데이터를 보관하는 방법 중 하나입니다

사용법

쿠키 등록

document.cookie = "user=John"

함수 활용

가져오기

function getCookie(name) {
  let matches = document.cookie.match(new RegExp(
    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
  ));
  return matches ? decodeURIComponent(matches[1]) : undefined;
}

쿠키를 가져오는 방법입니다.

내보내기

function setCookie(name, value, options = {}) {

options = {
  path: '/',
  // 필요한 경우, 옵션 기본값을 설정할 수도 있습니다.
  ...options
};

if (options.expires instanceof Date) {
  options.expires = options.expires.toUTCString();
}

let updatedCookie = encodeURIComponent(name) + "=" + encodeURIComponent(value);

for (let optionKey in options) {
  updatedCookie += "; " + optionKey;
  let optionValue = options[optionKey];
  if (optionValue !== true) {
    updatedCookie += "=" + optionValue;
  }
}

document.cookie = updatedCookie;
}

설정하기

setCookie('user', 'John', {'max-age': 31536000});
  • max-age : 최대값 31536000 (1년)
  • secure: true : 쿠키 암호화 관련 *참고자료

secure: true 를 추가했을 때 일부 PC에서 쿠키 자체가 저장이 안되는 문제가 있었습니다.
(false 로 변경해도 이슈 발생)

배열 활용

쿠키에 배열값 저장

var arr = ['foo', 'bar', 'baz'];
var json_str = JSON.stringify(arr);
setCookie('mycookie', json_str, {secure: true, 'max-age': 31536000});

쿠키에 배열값 불러오기

var json_str = getCookie('mycookie');
var arr = JSON.parse(json_str);

console.log(arr);

서브도메인 path 활용

function setCookie(name, value, days) {
  var expires = "";
  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    expires = "; expires=" + date.toUTCString();
  }
  var domain = "; domain=.www.light-coding.com"; // 전체 도메인을 지정합니다.
  document.cookie = name + "=" + (value || "")  + expires + domain + "; path=/";
}

서브도메인에서 만들어진 쿠키를 사용하려면 위의 함수와 같이
도메인을 만들어주어야 합니다

image 15
JS | 쿠키 활용법 2

라이브러리 활용

바닐라 자바스크립트

js-cookie

바로가기 : 링크

제이쿼리

바로가기 : 링크
사용법 : 바로가기

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다

클릭하여 복사