LoginSignup
8
7

More than 5 years have passed since last update.

JavaScript Web Storageについて

Last updated at Posted at 2016-11-24

Web Storageについてのメモ。

Web Storageとはなんぞ

ブラウザに実装されているKey-Value型のデータストア
- データサイズの上限:5MB
- データの有効期限:なし
- データ通信:発生しない(サーバ側に送られたりしない)

種類

①ローカルストレージ
localStorageプロパティで使う

  • オリジン単位でデータを管理。
  • ウインドウやタブをまたいでデータの受け渡しが可能。
  • ブラウザを閉じてもデータは残る

②セッションストレージ
sessionStorageプロパティで使う

  • 現在のブラウザが開かれている間データが保持される。
  • ブラウザが閉じられればデータは破棄される。
  • ウインドウやタブをまたいでのデータ受け渡しはできない。

どう使うか

chromeでは↓をコンソールに貼り付ければ実行可能

{
    //ストレージの定義
    const storage = localStorage;

    /**
     * 値のセット手段
     */
    storage.setItem('test', 'hoge');
    storage.test2 = 'fuga';
    storage['test3'] = 'hogefuga';

    /**
     * 値の取り出し方
     */
    console.log(storage.getItem('test'));
    console.log(storage.test2);
    console.log(storage['test3']);
}

データの削除

storage.removeItem('test');
delete storage.test2;
delete storage['test3'];

全てのデータを削除

storage.clear();

データを取り出す

{
    const storage = localStorage;

    for (let i=0, limit=storage.length; i<limit; i++) {
        let k = storage.key(i);
        let v = storage[k];
        console.log(`${k} : ${v}`);
    } 
}

オブジェクトを保存する

{
    const storage = localStorage;
    const test = {a: 'hoge', b: 'fuga'};

    storage.setItem('item', JSON.stringify(test));

    const data = JSON.parse(storage.getItem('item')); 

    console.log(data.a);
    console.log(data.b);
}

モジュール例

es6ではうまく書ききれなかったのでひとまずes5で

var Store = function(appName) {
    this.app = appName;

    this.storage = localStorage;

    this.data = JSON.parse(this.storage[this.app] || '{}');
};

Store.prototype = {
    getItem: function (key) {
        return this.data[key]
    },

    setItem: function (key, value) {
        this.data[key] = value;
    },

    save: function () {
        this.storage[this.app] = JSON.stringify(this.data);
    }
};

//モジュールの利用
var sampleStore = new Store('test');
sampleStore.setItem('item', 'hoge');
console.log(sampleStore.getItem('item'));
sampleStore.save(); //確認

イベントリスナーの登録

var sampleStorage = localStorage;
window.addEventListener('sampleStorage', function (e) {
    console.log(`changed: ${e.key}`);
    console.log(`previous: ${e.oldValue}`);
    console.log(`after: ${e.newValue}`);
    console.log(`event fired page: ${e.url}`);
});
sampleStorage.test2 = 'hoge';

同じurlのページ開いて、コンソールで検証してみてください。。

こんなことに使ってるから便利等あれば教えてください、、
こちらからは以上です。

8
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
7