session storageとlocal storage

web storageは同一オリジンでデータを保存しています。同階層、下ディレクトでも使えます。sessionStorage(タブが閉じられるまで)とloacalStorage(ブラウザ自体に保存)の二種類があります。chrome developer toolのapplicationパネルで確認できます。

%e7%84%a1%e9%a1%8c

      <script>
      (function(){
        if (typeof(Storage) === "undefined"){
          alert("web storage not supported");
        } else {
          // console.log("supported");
          // var s = sessionStorage;
          var s = localStorage;
          s.setItem('name', 'okada');
          console.log(s.getItem('name'));
        }
      })();
      </script>

setItemと削除

      <script>
      (function(){
        if (typeof(Storage) === "undefined"){
          alert("web storage not supported");
        } else {
          var ls = localStorage;
          var ss = sessionStorage;

          ls.setItem('yamada', 20);
          ls.setItem('kimura', 69);

          ss.setItem('color', 'pink');
          ss.setItem('shape', 'cube');

          // removeItem(key)
          // clear()

          ls.removeItem('yamada');
          ss.clear();
        }
      })();
      </script>

lengthとkey

      <script>
      (function(){
        if (typeof(Storage) === "undefined"){
          alert("web storage not supported");
        } else {
          var s = localStorage;

          s.setItem('okamoto', 90)
          s.setItem('murata', 60)
          s.setItem('ito', 50)

          for (var i = 0; i < s.length; i++){
            console.log(s.key(i) + ':' + s.getItem(s.key(i)));
          }


        }
      })();
      </script>

JSON(javascript object nation)

      <script>
      (function(){
        if (typeof(Storage) === "undefined"){
          alert("web storage not supported");
        } else {
          var s = localStorage;

          var user = {
            name: 'yoshida',
            score: 50
          };

          s.setItem('user', JSON.stringify(user));
          console.dir(JSON.parse(s.getItem('user')));
        }
      })();
      </script>

データの整合性

      <script>
      (function(){
        if (typeof(Storage) === "undefined"){
          alert("web storage not supported");
        } else {
          var s = localStorage;
          s.setItem('name','kurumada');

          window.addEventListener('storage', function(e){
            console.log(e.key + ':' + e.oldValue + '->' + e.newValue);
          });
        }
      })();
      </script>