개발자의 길

[자바스크립트] 쿠키 사용 본문

2. JS

[자바스크립트] 쿠키 사용

자르르 2010. 4. 7. 15:10


네스케이프 쿠키는 클라이언트에  cookies.txt 라는 파일에 영구적데이터를 저장하는 메카니즘이다
HTTP 는 무상태 프로토콜이기때문에,쿠키가 하나의 클라이언트에서 온 요청과 다음 요청사이에 정보를 유지하는 방법을 제공한다.
각각의 쿠키는 선택적인 소멸시간을 가지는 작은 정보의 항목이며 다음과 같은 형식으로 쿠키파일에 추가된다

           name=value;expires=expDate;

-name 은 저장될 자료의 이름이다.
-value 는 name의 값이다.
name과 value가 세미콜론(;) 콤마(,) 공백(space)문자를 가지고 있다면
그러한 특수 문자를 encode화기위해 escape함수를 사용해야 하며
특수문자를 decode하기 위해서는 unescape 함수를 사용해야 한다.
-expDate 는 소멸 날짜이다.  GMT 날짜 형식이다.


Date의 메소드 toGMTString 에 의해 반환되는 date 문자열은 쿠키소멸날짜를  설정하는데 사용될수 있다.
소멸날짜는 선택적인 파리미터이며 쿠키를 얼마나 오랫동안 유지하는지를 지정하는 것이다.
expDate 가 지정되지 않았다면 유저가 현재 브라우저(Navigator) 세션을 종료할때 쿠키가 소멸된다.
Navigator는 소멸날짜가 아직 지나지 않았을때만 쿠키를 유지하고 값을 구해온다.


-- escape 와 unescape 를 참조하라


----제한사항-- 쿠키는 다음과 같은 제한이 있다

쿠키파일에 300 개의 쿠키유지
1쿠키당 4 kbyte(1쿠키=쿠키이름+쿠키값)
1서버 또는 1 도메인에 대하여 20 개의 쿠키가 가능하다.


Cookies는 서버상의 하나이상의 디렉토리와 관련되어 질수 있다.
만약에 서버상의 파일들이 모드 하나의 디렉토리에 존재 한다면,쿠키와 디렉토리와의 관계를 걱정할 필요는 없다.
만약에 서버상의 파일들이 서로 다른 디렉토리에 존재한다면, 각각의 쿠키를 위해 추가적인 경로인자(path parameter)를
사용할 필요가 있다.


--- 자바스크립트를 이용한 쿠기
document.cookie  property는 쿠키의 모든 이름(name)과 값(value)을 유지하고 있는 문자열(String)이다.

---쿠키를 자바스크립트로 다루기
   1. 쿠키값 설정, (옵션으로 소멸날짜를 지정할수 있다)
   2. 쿠키값 얻기, (쿠키이름을 지정한다)


쿠키값을 설정하기위해 사용자가 자바스크립트 함수를 예제로 작성했다.
function setCookie(name, value, expire) {
  document.cookie = name + "=" + escape(value) + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()));
}

escape 함수는 값(value)문자열에 있는 특수문자(semicolons, commas, spaces)를 encode 하기위해 사용했다
name에는 특수한 문자가 포함되지 않을것 같아서 escape함수를 사용하지 않았다.


function getCookie(Name) {
  var search = Name + "=";
  if (document.cookie.length > 0) {                    // if there are any cookies
     offset = document.cookie.indexOf(search);
     if (offset != -1){                                               // if cookie exists
        offset += search.length;                             // set index of beginning of value
        end = document.cookie.indexOf(";", offset);   // set index of end of cookie value
        if (end == -1)
           end = document.cookie.length;
        return unescape(document.cookie.substring(offset, end));
     }
  }
}

indexOf(search) 함수는 document.cookie의 멤버함수가 아니다.
document.cookie 는 문자열속성일 뿐이다.  따라서 함수를 가지고 있지 않다.
indexOf(..)함수는 String 의 멤버함수 이다.
length도한 String의 멤버변수이다.
unescape함수는 쿠키값에 있을 수 있는 특수문자(semicolons, commas, spaces)를 decode하기 위해 사용했다.

 

(여기에 예제가 있다.)

위 부분에서 정의한 setCookie와 getCookie함수를 사용해서, 사용자가 당신의 페이지를 방문 했을때 ''등록''하기 위해 입력할수 있는 페이지를 만들수 있다.
사용자가 1년안에 당신의 페이지를 다시 방문한다면 , 사용자는 환영인사말을 볼 것이다.
그러기 위해서  document의 HEAD부분에 추가적인 하나의 함서를 정의할 필요가 있다.
register라는 이름으로 추가하는 함수는 ''TheCoolJavaScriptPage'' 라는 name을 가지는 cookie를 만들고 value를 인자로 전달한다.


function register(cookieValue) {
  var today = new Date();
  var expires = new Date();
  expires.setTime(today.getTime() + 1000*60*60*24*365);
  setCookie("TheCoolJavaScriptPage", cookieValue, expires);
}


document 의 BODY부분에서  위 부분에서 정의한 getCookie함수를 사용해서 ''TheCoolJavaScriptPage''에 대한 쿠키가 존재하는지를
검사해서 존재한다면 인사말을 보여준다
cookie를 추가하기 위해 register라는 함수를호출 하는 form 도 있다.
onClick 이벤트핸들러에서는  history.go(0) 을 호출해서 현재 페이지를 갱신해준다.

<BODY>
<H1>Register Your Name with the Cookie-Meister</H1>
<P>
<SCRIPT>
var yourname = getCookie("TheCoolJavaScriptPage")
if (yourname != null)
  document.write("<P>Welcome Back, ", yourname)
else
  document.write("<P>You haven''t been here in the last year...")
</SCRIPT>

<P> Enter your name. When you return to this page within a year, you will be greeted with a personalized greeting.
<BR>
<FORM onSubmit="return false">
Enter your name: <INPUT TYPE="text" NAME="username" SIZE= 10><BR>

<INPUT TYPE="button" value="Register"
  onClick="register(this.form.username.value); history.go(0)">
</FORM>

 

-------------------------------------------
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JAVASCRIPT">

function setCookie(name, value, expire) {
  document.cookie = name + "=" + escape(value) + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()));
}


function getCookie(Name) {
  var search = Name + "=";
  if (document.cookie.length > 0) {                    // if there are any cookies
     offset = document.cookie.indexOf(search);
     if (offset != -1){                                               // if cookie exists
        offset += search.length;                             // set index of beginning of value
        end = document.cookie.indexOf(";", offset);   // set index of end of cookie value
        if (end == -1)
           end = document.cookie.length;
        return unescape(document.cookie.substring(offset, end));
     }
  }
}


function register(cookieValue) {
  var today = new Date();
  var expires = new Date();
  expires.setTime(today.getTime() + 1000*60*60*24*365);
  setCookie("TheCoolJavaScriptPage", cookieValue, expires);
}
</SCRIPT>
</HEAD>
<BODY>
<H1>당신의 이름을 Cookie-Meister 로 등록합니다.</H1>
<p>
           <SCRIPT LANGUAGE="JAVASCRIPT">
                       var yourname = getCookie("TheCoolJavaScriptPage") ;
                       if (yourname != null)
                                   document.write("<P>다시 온걸 환영합니다, ", yourname);
                       else
                                               document.write("<P>지난해에 방문한적이 없군요....");
           </SCRIPT>

<p>이름을 입력한다.1년안에 이 페이지를 다시 방문하면 인사말과 함께 반겨줄것이다.
<BR>

<FORM onSubmit="return false">
           이름입력: <INPUT TYPE="text" NAME="username" SIZE= 10><BR>
           <INPUT TYPE="button" value="Register" onClick="register(this.form.username.value); history.go(0)">
</FORM>

</BODY>
</HTML>



이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
공유하기 링크
Comments