쓸만한 글

쿠키 다루기

봄돌73 2006. 4. 25. 10:24

//쿠키 생성

function setCookie(name, value) {
    var argc = setCookie.arguments.length
    var argv = setCookie.arguments
    var expires = (argc > 2) ? argv[2] : null
    var path = (argc > 3) ? argv[3] : "/"
    var domain = (argc > 4) ? argv[4] : null
    var secure = (argc > 5) ? argv[5] : false
 alert(expires);
 alert(path);
 alert(domain);
 alert(secure);
    document.cookie = name + "=" + escape(value) +
                              ((expires==null) ? "" : ("; expires=" + expires.toGMTString())) +
                              ((path==null) ? "" : ("; path=" + path)) +
                              ((domain==null) ? "" : ("; domain=" + domain)) +
                              ((secure==true) ? "; secure" : "")
}

//쿠키 불러오기

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 "";
}

//쿠키 삭제

function DeleteCookie (name) { 
  var argc = DeleteCookie.arguments.length
  var argv = DeleteCookie.arguments
  var expires = (argc > 2) ? argv[2] : null
  var path = (argc > 3) ? argv[3] : "/"
  var domain = (argc > 4) ? argv[4] : null
  var secure = (argc > 5) ? argv[5] : false
        var exp = new Date(); 
        exp.setTime (exp.getTime() - 1); 
        var cval = getCookie (name); 
        document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString() +
                              ((path==null) ? "" : ("; path= /" + path)) +
                              ((domain==null) ? "" : ("; domain=" + domain)) +
                              ((secure==true) ? "; secure" : "")
}





출처 : http://blog.naver.com/enanim?Redirect=Log&logNo=80023798542