JavaScript/이론

[Javascript] Cookie

sirius 2021. 3. 16. 10:43

1. Cookie

 

사용자가 웹 사이트를 방문할 경우 해당 사이트에서 사용자의 컴퓨터에 저장하는 정보

쿠키는 다른 페이지들 사이에서 세션정보를 유지하는데 사용

쿠키의 형태는 웹 스토리지와 동일하게 키와 값으로 이루어져 있으며, 사용자 로컬에 텍스트 형태로 저장

 

2. Cookie 특징

 

하나의 웹 브라우저에 쿠키를 300개 이상 보관할 수 없음

동일 웹서버에 쿠키를 20개 이상 보관할 수 없음

각 쿠키의 크기는 4KByte를 넘지 못함

 

3. Cookie 의 property

 

document.cookie="name=value[; expires=expires] [; path=path] [; domain=domain] [; secure]";

 

property  description 
 name=value   쿠키의 이름과 값을 설정
 expires=date   쿠키가 만료되는 기간을 설정. expires값이 설정되지 않는다면 브라우저가 닫히는 순간 소멸
 path=path   쿠키가 적용될 사이트의 패스를 지정하고자 하는 경우 이용
 domain=domain   쿠키를 적용할 도메인을 지정
 secure    SSL을 이용하여 서버에 쿠키를 전송

 

<script type="text/javascript">
    var Cookie = {

        initData : [],

        setCookie : function(name, value, options) {

            options = options || {};

            this.initData = [ escape(name) + '=' + escape(value) ];

            if (options.expires) {
                if (typeof options.expires === 'object'
                        && options.expires instanceof Date) {
                    var date = options.expires;
                    var expires = "expires=" + date.toUTCString();
                    this.initData.push(expires);
                }
            } else if (options.expires_day) {
                var date = new Date();
                var day = 24 * 60 * 60 * 1000;
                date.setTime(date.getTime() + options.expires_day * day);
                var expires = "expires=" + date.toUTCString();
                this.initData.push(expires);
            }

            if (options.domain) {
                this.initData.push("domain=" + options.domain);
            }

            if (options.path) {
                this.initData.push("path=" + options.path);
            }

            if (options.secure === true) {
                this.initData.push("secure");
            }

            var cookieString = this.initData.join('; ');
            console.log(cookieString);
            document.cookie = this.initData.join('; ');
        },

        getCookie : function(name) {
            var cookie = document.cookie
            var cookie_array = cookie.split(";");

            if (cookie_array.length) {
                for (var index in cookie_array) {
                    var cookiePair = cookie_array[index].split("=");

                    if (cookiePair[0].trim() == name)
                        return cookiePair[1]
                }

                alert(name + " do not existed")
            } else {
                alert("Cookie is empty")
            }
        },


        delCookie : function(name, options) {
            this.setCookie(name, "", options);
        }
    };

    function setCookie() {
        var cookie_name = document.getElementById("cookiename").value;
        var cookie_value = document.getElementById("cookievalue").value;
        if (cookie_name == "" || cookie_value == "") {
            alert("insert Cookie Name or Cookie Value");
            return;
        }

        Cookie.setCookie(cookie_name, cookie_value, {
            //expires : new Date(),
            domain : 'localhost',
            path : '/',
            secure : false
        });

        alert(document.cookie);
    }

    function ReadCookie() {
        var cookie_name = document.getElementById("getcookiename").value;

        if (cookie_name == "") {
            alert(document.cookie);
            return;
        }
        var cookie_value = Cookie.getCookie(cookie_name);
        alert(cookie_value);
    }

    function Deletecookie() {
        var cookie_name = document.getElementById("delcookiename").value;
        Cookie.delCookie(cookie_name, {
            expires_day : -1,
            domain : 'localhost',
            path : '/',
            secure : false
        });
    }

    function CheckCookie() {
        alert(document.cookie);
    }
</script>