javascript로 cookie를 다루는 방법

이것은 auction 사이트에서 본 코드인데, 다른 사이트에서도 동일한 함수들이 보이는 것으로 봤을때 (1) 표준이거나 (2) 동일한 개발자가 만든 사이트들이다.

아무튼...


1. 아래와 같은 방법으로 쿠키를 쓴다.

function setCookie( name, value, expiredays ) {
  var endDate = new Date();
  endDate.setDate(endDate.getDate() + expiredays);
  document.cookie = name + "=" + escape( value ) +

    "; path=/; expires=" + endDate.toGMTString() + ";" ;
}




2. 아래와 같은 방법으로 쿠키를 읽는다.

function getCookie( name ) {
  var nameOfCookie = name + "=";
  var x = 0;
  while ( x <= document.cookie.length ) {
    var y = (x+nameOfCookie.length);
    if ( document.cookie.substring( x, y ) == nameOfCookie ) {
      if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 )
        endOfCookie = document.cookie.length;
      return unescape( document.cookie.substring( y, endOfCookie ) );
    }
    x = document.cookie.indexOf( " ", x ) + 1;
    if ( x == 0 )
      break;
  }
  return "";
}




3. 쿠키를 활용해서 팝업을 연다.
function openPopup( name ){
  if( getCookie( name ) != 'Y' )
    $('#popup').show();
}




4. 쿠키를 활용해서 팝업을 닫는다.

function closePopup() {
  setCookie("appBanner" , "Y" , 1);
  $('#popup').hide();
  return false;
}