JavaScript (HTML5): データを記憶する

javascript: snippet-cookie.js

(function() {
	function SnippetCookie() {};
	SnippetCookie.prototype.setCookie = function(key, value, expireDays)
	{
		var path = location.pathname,
			paths = [];
			paths = path.split("/");
		if (paths[paths.length-1] != "") {
			paths[paths.length-1] = "";
			path = paths.join("/");
		}
		var s = "";
			s += key + "=" + escape(value);
			s += "; path="+ path;
		
		var date = new Date(60*60*24*1000*expireDays + new Date().getTime());
		if (expireDays){
			s += "; expires=" + date.toUTCString() + "; ";
		} else {
			s += "; ";
		}
		
		document.cookie=s;
	};
	SnippetCookie.prototype.getCookie = function(key)
	{
		var st = "",
			ed = "";
		if (document.cookie.length>0) {
			st = document.cookie.indexOf(key + "=");
			if (st != -1) {
				st = st + key.length + 1;
				ed = document.cookie.indexOf(";",st);
				if(ed == -1) ed=document.cookie.length;
				return unescape(document.cookie.substring(st,ed));
			}
		}
		return "";
	};
	
	function loaded() {
		window.snippet = new SnippetCookie();
		window.snippet.setCookie("name", "feb", 7);
		window.snippet.setCookie("num", 19, 7);
		console.log(window.snippet.getCookie("name") + window.snippet.getCookie("num"));
		window.snippet.setCookie("name", null, 7);
		window.snippet.setCookie("num", null, 7);
		console.log(window.snippet.getCookie("name") + window.snippet.getCookie("num"));
	}
	
	if(document.addEventListener){
		document.addEventListener("DOMContentLoaded", loaded, false);
	} else if(/msie/.test(navigator.userAgent.toLowerCase())){
		try {
			document.documentElement.doScroll("left");
		} catch(error){
			setTimeout(arguments.callee, 0);
			return;
		}
		loaded();
	}
}).call(this);

Output:

snippet-cookie.js:45 feb19
snippet-cookie.js:48 nullnull