Please Enable JavaScript!
Gon[ Enable JavaScript ]

쿠키정보를 확인하고 활용할수 있는 코드

웹 프로그래밍/자바스크립트
반응형

전체 쿠키 정보를 Text 로 출력한다 . 모든 쿠키에 대한 정보를 알아볼려면  document.cookie 를 호출하면 된다. 집어 넣는 곳은 cookieOut 이라는 DIV 내에 Text 를 출력하는  로직이다.
// 모든 쿠키출력
function viewCookie()
{
   if( document.cookie.length > 0 )
      cookieOut.innerText = document.cookie;
   else
      cookieOut.innerText = "저장된 쿠키가 없습니다.";
}
// 출력화면
<DIV id = "cookieOut"></DIV>


저장된 쿠키값을 쿠키명으로 검색해서 넘겨주는 함수이다.
// param : 쿠키명
// return : 쿠키값
function getCookie( cookieName )
{
   var search = cookieName + "=";
   var cookie = document.cookie;

   // 현재 쿠키가 존재할 경우
   if( cookie.length > 0 )
   {
       startIndex = cookie.indexOf( cookieName );// 해당 쿠키명이 존재하는지 검색후 위치정보를 리턴.

       if( startIndex != -1 ) // 존재한다
      {
         startIndex += cookieName.length;// 값을 얻어내기 위해 시작 인덱스 조절
         endIndex = cookie.indexOf( ";", startIndex );// 값을 얻어내기 위해 종료 인덱스 추출
         if( endIndex == -1) endIndex = cookie.length; // 만약 종료 인덱스 못찾으면 쿠키 전체길이로 설정

         return unescape( cookie.substring( startIndex + 1, endIndex ) );// 쿠키값을 추출하여 리턴
      } else {
         return false; // 존재하지 않을때
      }
   } else {
      return false; // 쿠키 아예없을때
   }
}

쿠키값을 설정한다. 파라미터로는 쿠키명, 쿠키값, 쿠키날짜를 넘긴다
function setCookie( cookieName, cookieValue, expireDate )
{
   var today = new Date();
   today.setDate( today.getDate() + parseInt( expireDate ) );
   document.cookie = cookieName + "=" + escape( cookieValue ) + "; path=/; expires=" +                
           today.toGMTString() + ";"
}


쿠키명을 넘겨 해당하는 쿠키를 삭제한다
function deleteCookie( cookieName )
{
   var expireDate = new Date();
 
   //어제 날짜를 쿠키 소멸 날짜로 설정한다.
   expireDate.setDate( expireDate.getDate() - 1 );
   document.cookie = cookieName + "= " + "; expires=" + expireDate.toGMTString() + "; path=/";
}




반응형
Posted by 녹두장군1
,