javascriptでcookieを扱うクラスを書いてみた
JavaScriptでクッキーを扱う方法を学習するためにクッキー関係の操作をまとめたクラスを書いてみた。
// cookieWrap.js /* * Firefox3,Google Chromeでのみ動作確認。 */ function Cookie() { this.initialize.apply(this, arguments); } Cookie.prototype = { initialize: function() { this.storage = this.expand(); }, // cookie文字列->連想配列 expand: function() { if (document.cookie == "") return {}; var hash = {}; var list = document.cookie.split(";"); for (var i = 0; i < list.length; i++){ var pair = list[i].split("="); hash[pair[0]] = unescape(pair[1]); } return hash; }, // 連想配列->cookie文字列 fold: function() { var list = []; for (var key in this.storage){ var val = this.storage[key]; if (key != "expires") val = escape(val); list.push([key, val].join("=")); } return list.join(";"); }, set: function(key, val) { this.storage[key] = val; document.cookie = this.fold(); }, get: function(key) { for (var k in this.storage) if (k == key) return unescape(this.storage[k]); return null; }, dump: function() { return this.storage; }, // // expire関係 // expireFromNow: function(msec) { var gmts = new Date(new Date().getTime() + msec).toGMTString(); this.set("expires", gmts); }, expireSecond: function(seconds) { this.expireFromNow(seconds *1000); }, expireMinite: function(minites) { this.expireSecond(minites *60); }, expireHour: function(hours) { this.expireMinite(hours *60); }, expireDay: function(days) { this.expireHour(days *24); }, expireDate: function(d) { // 特定の日付時刻にリセット this.expireFromNow(datetime.getTime()); }, };
このクラスを使ってカウンタを実装してみた。"you visited N time(s)"と回数が表示される。
<html> <head> <meta http-equiv="content-type" content="text/html"/> <title>cookie counter</title> <script src="./cookieWrap.js"></script> <script> function $(tid){ return document.getElementById(tid); } function main() { var cookie = new Cookie(); var count = cookie.get("count"); if (count == null) count = 0; cookie.set("count", parseInt(count) + 1); cookie.expireSecond(10); $("container").innerHTML = ["you visit ", cookie.get("count"), " time(s)"].join(""); //setTimeout("location.reload();", 1000); } </script> </head> <body onLoad="main();"> <div id="container"></div> </body> </html>