PROWAREtech

articles » current » javascript » cookie-utility

JavaScript: Cookie Utility

A utility to create, access and delete cookies from the browser.

Here is an object for creating and deleting cookies.

var Cookies = {
	get: function (name) {
		var cookieName = name + "=";
		var cookieStart = document.cookie.indexOf(cookieName);
		var cookieValue = null;
		if (cookieStart > -1) {
			var cookieEnd = document.cookie.indexOf(";", cookieStart);
			if (cookieEnd == -1) {
				cookieEnd = document.cookie.length;
			}
			cookieValue = document.cookie.substring(cookieStart + cookieName.length, cookieEnd);
		}
		return cookieValue ? decodeURIComponent(cookieValue) : cookieValue;
	},
	set: function (name, value, days_when_expired, path, domain, secure) {
		var cookieText = name + "=" + encodeURIComponent(value);
		if (days_when_expired) {
			var date = new Date();
			date.setTime(date.getTime() + (days_when_expired * 24 * 60 * 60 * 1000));
			cookieText += "; expires=" + date.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, "", -1, path, domain, secure);
	}
};

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE