cookie toolbox

by Laurens Maneschijn

HTML

<h1>various cookie get/set/clear functions; see JS panel.</h1>

<form id="form_save">
	store new cookie (or overwrite existing key):
	key    : <input name="key" value="">
	value  : <input name="value" value="">
	expire : <input name="expire" value="">
	path   : <input name="path" value="/">
	<input type="submit">
</form>
<form id="form_remove">
	remove cookie:
	key : <input name="key" value="">
	<input type="submit">
</form>

<h2>current cookie data:</h2>
<button id="buttonupdate">update</button>
<textarea id="ta1"></textarea>
<textarea id="ta2" rows="4"></textarea>

<p>
	links:
	<a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie/Simple_document.cookie_framework" >1</a>
</p>

CSS

* { box-sizing: border-box }

h1,h2,h3,h4,h5,h6 {
	font-size: 1em;
	margin:0;
}

form {
	display: block;
	margin: 2px;
	padding: 2px;
	background: #eee;
	border: 1px solid #888;
	border-radius: 3px;
}
textarea {
	width: 100%;
}

JavaScript

function getCookies() {
	if(!document.cookie){ return {}; }
	var o = {}, i, m, key, value, c_arr = document.cookie.split(';'), re = /\s*([^=]+)=(.*)/;
	for (i=0; i<c_arr.length; i++) {
		m = c_arr[i].match(re);
		if (m) {
			name = m[1];
			value = m[2];
			name = unescapeCookieKey(name);
			value = unescapeCookieValue(value);
			o[ name ] = value;
		}
	}
	return o;
}
function getCookie(name) {
	return getCookies()[name];
}
function eraseCookie(name, path) {
	path = path || '/';
	name = escapeCookieKey(name);
	document.cookie = name+'=; Max-Age=-99999999; path=' + path;
}
function eraseCookies(path){
	for(var name in getCookies()){
		eraseCookie(name, path);
	}
}
function setCookie(name, value, days, path) {
	var expires = "";
	value = value || "";
	path = path || "/";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days*24*60*60*1000));
		expires = "; expires=" + date.toUTCString();
	}
	name = escapeCookieKey(name);
	value = escapeCookieValue(value);
	document.cookie = name + "=" + value + expires + "; path=" + path;
}
function setCookie_v2(name, value, expire, path) {
	name = name || "";
	value = value || "";
	path = path || "/";


	var parts = [];

	name = escapeCookieKey(name);
	value = escapeCookieValue(value);
	parts.push(name + "=" + value);

	parts.push("path=" + path);

	if (typeof expire !== 'undefined') {
		date = parseDate(expire);
		if (date) {
			parts.push("expires=" + date.toUTCString());
		}
	}
	document.cookie = parts.join('; ');
}

// NB: URI encode is the general accepted way of safely escaping cooky key or value.
// TODO: perhaps a better alternative can be found?
// see for example:
// https://stackoverflow.com/questions/6869866/do-i-need-to-escape-cookie-values-when-setting-from-servlet-api
function escapeCookieKey(v){
	return encodeURIComponent(v);
}

function unescapeCookieKey(v){
	return decodeURIComponent(v);
}

function escapeCookieValue(v){
	return encodeURIComponent(v);
}

function...