説明
		
			
			
		
JavaScriptではデータを保存するためのクッキーファイルへの書き込み、読み出しをサポートしています。クッキーファイルはdocument.cookieで参照することができます。クッキーへの書き込みはデータ名とデータ値、そしてデータの保存期限を指定します。データの書き込み数には上限があるので、大量のデータ保存には向きません。また、恒久的に保存されるわけではありません。長期間にデータを保存する場合にはCGI経由でサーバーに保存する必要があります。
クッキーからの読み出しはdocument.cookieに該当する名前のデータがあるかどうかindexOf()を使って調べます。名前があった場合には、データ値を取得します。
				 
			
				
				
		<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
			<html>
			 <head>
			  <meta http-equiv="content-type" content="text/html;charset=utf-8">
			  <title>JavaScript Sample</title>
			  <link rel="stylesheet" type="text/css" href="main.css" media="all">
			  <script type="text/javascript" src="main.js"></script>
			 </head>
			 <body>
			  <h1>クッキーのデータの読み書き</h1>
			  <form action="./cookie.cgi" method="get" name="mainForm">
			   <input type="text" id="userData" name="userData" value="215"><br>
			   <input type="button" id="writeButton" value="書き込み">
			   <input type="button" id="readButton" value="読み込み">
			  </form>
			  <div id="result">結果:</div>
			 </body>
			</html>
window.onload = function(){
			 document.getElementById("writeButton").onclick = function(){
			  var data = document.getElementById("userData").value;
			  cookie.write("userComment", data, 30);
			 }
			 document.getElementById("readButton").onclick = function(){
			  var data = cookie.read("userComment");
			  document.getElementById("result").innerHTML = "クッキーデータは「"+data+"」";
			 }
			}
			var cookie = {
			 write : function (theName__,theValue__,theDay__){
			  if ((theName__ != null) && (theValue__ != null)){
			   var expDay__ = "Wed, 01 Jan 2020 18:56:35 GMT"; // 指定されない場合とりあえず2020年
			   if (theDay__ != null){
			    theDay__ = eval(theDay__); // 文字列の場合でも数値にする(念のため)
			    var setDay = new Date();
			    setDay.setTime(setDay.getTime()+(theDay__*1000*60*60*24));
			    expDay__ = setDay.toGMTString();
			   }
			   document.cookie = theName__ + "="+escape(theValue__)+";expires="+expDay__;
			   return true;
			  }
			  return false;
			 },
			 read : function (theName__){
			  theName__ += "="; // =を追加して検索の手抜きをする
			  theCookie__ = document.cookie+";"; // 検索時最終項目で-1になるのを防ぐ
			  start__ = theCookie__.indexOf(theName__); // 指定された名前を検索する
			  if (start__ != -1){
			   end__ = theCookie__.indexOf(";",start__);
			   return unescape(theCookie__.substring(start__+theName__.length,end__));
			  }
			  return false;
			 }
			}