サンプル・プログラム
誕生日当てゲーム
実際のゲームは暗算で行うのだが、この計算の仕組みをJavaScriptでプログラミングしてみた。
保存 ボタンを押下すると、誕生月と日をローカルドライブに保存する。ブラウザを終了してもデータは消えず、このページを再度表示すると、保存した値が読み込まれるという仕組みである。
サンプル・プログラムの解説
getElementById メソッドを使い、FORMに入っている月と日を取得する。
HTML 5の localStorage に対応していれば、プロパティ localStorage が真となる。これを利用し、setItem メソッドを使って、 localStorage にデータを保存する。
setItem メソッドの第1引数はキー情報(変数名)、第2引数は値である。
一方、ロード時に実行する関数で、getItem メソッドを使い、localStorage に保存したデータを取り出す。
0011: <script type="text/javascript">
0012: <!--
0013: //localStorageから呼び出し
0014: window.onload = function() {
0015: var month = '';
0016: var day = '';
0017: if (localStorage) {
0018: month = localStorage.getItem("birthgame_month");
0019: day = localStorage.getItem("birthgame_day");
0020: }
0021: document.getElementById('month').value = month;
0022: document.getElementById('day').value = day;
0023: }
0024:
0025: //計算
0026: function calc() {
0027: var month = parseInt(document.getElementById('month').value);
0028: var day = parseInt(document.getElementById('day').value);
0029: var n1 = month * 4;
0030: var n2 = n1 + 9;
0031: var n3 = n2 * 25;
0032: var n4 = n3 + day;
0033: var n5 = n4 - 225;
0034: document.getElementById('n1').value = n1;
0035: document.getElementById('n2').value = n2;
0036: document.getElementById('n3').value = n3;
0037: document.getElementById('n4').value = n4;
0038: document.getElementById('n5').value = n5;
0039: }
0040:
0041: //localStorageに保存
0042: function saveItem() {
0043: var month = document.getElementById('month').value;
0044: var day = document.getElementById('day').value;
0045: if (localStorage) {
0046: localStorage.setItem("birthgame_month", month);
0047: localStorage.setItem("birthgame_day", day);
0048: }
0049: }
0050: -->
0051: </script>
Web Storageについて
名称 | 特 徴 |
---|---|
sessionStorage | 一時的にデータを保存する。 ウィンドウを閉じるタイミングで消える。 同じページを複数のウィンドウで開いた場合、別々に保存される。 |
localStorage | 明示的に消去しない限り、データをローカル環境に保持し続ける。 |
つまり、プロトコル、ドメイン、ポート番号のいずれかが異なれば、キー情報が同じでも異なるデータ格納領域となる。"https://www.pahoo.org/e-soul/webtech/js01/program/birthgame.html" と "https://www.pahoo.org/index.html" は同じオリジンである。
また、オリジンが異なるデータ領域へのアクセスをさせないことで、セキュリティを保っている。
参考サイト
- Web Storageを使ってみる:FreeStyleVision
- HTML5のlocalStorageの使い方のまとめ:小粋空間