본문 바로가기
개발/Javascript

Javascript SetCookie GetCookie

by 혈중마라농도 2022. 1. 12.
function GetCookie(key) {
    var arg = key + "=";
    var argLength = arg.length;
    var cookieLength = document.cookie.length;
    var i = 0;
    var j = 0;
    while (i < cookieLength) {
        j = i + argLength;
        if (document.cookie.substring(i, j) == arg) {
            var endString = document.cookie.indexOf(";", j);
            if (endString == -1) {
                endString = document.cookie.length;
            }
            return unescape(document.cookie.substring(j, endString));
        }
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0) {
            break;
        }
    }
    return null;
}

function SetCookie(key, value) {
    var argv = arguments;
    var argc = arguments.length;
    var expires = (argc > 2) ? argv[2] : null;
    var domain = (argc > 3) ? argv[3] : null;
    var path = (argc > 4) ? argv[4] : '/';
    var secure = (argc > 5) ? argv[5] : false;
    if (expires != null) {
        var date = new Date();
        date.setTime(date.getTime() + (expires * 24 * 60 * 60 * 1000)) //days
        expires = date;
    }
    document.cookie = key + "=" + escape(value) + ((expires === null) ? "" : ("; expires=" + expires.toGMTString())) + ((path === null) ? "" : ("; path=" + path)) + ((domain === null) ? "" : ("; domain=" + domain)) + ((secure === true) ? "; secure" : "");
}
반응형

댓글