js 조작 쿠키

라 는 책 에서 코드 를 발 견 했 는데 참고 할 만하 다.

	var CookieUtil = {
		get: function(name) {
			var cookie = document.cookie;
			var cookieName = encodeURIComponent(name) + "=";
			var start = cookie.indexOf(cookieName);
			var value = null;
			if (start > -1)
			{
				var end = cookie.indexOf(";", start);
				if (end == -1)
					end = cookie.length;
				value = decodeURIComponent(cookie.substring(start + cookieName.length, end));
			}
			return value;
		},
		set: function(name, value, expires, path, domain, secure) {
			var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
			if (expires instanceof Date)
				cookieText += "; expires=" + expires.toGMTString();
			if (path)
				cookieText += "; path=" + path;
			if (domain)
				cookieText += "; domain=" + domain;
			if (secure)
				cookieText += "; secure";
				
			document.cookie = cookieText;
		},
		unset: function(name, path, domain, secure) {
			this.set(name, "", new Date(0), path, domain, secure);
		}
	};

	// test
	CookieUtil.set("name","tony");
	alert(CookieUtil.get("name"));
	CookieUtil.unset("name");
	alert(CookieUtil.get("name"));

좋은 웹페이지 즐겨찾기