Storage
        
        
          
                Baseline
                
                  Widely available
                
                
              
        
        
        
          
                
              
                
              
                
              
        
        
      
      This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
Storage はウェブストレージ API のインターフェイスで、特定のドメインのセッションストレージまたはローカルストレージへのアクセス機能を提供して、例えば保存されているデータアイテムを追加、変更、削除することができます。
例えば、ドメインのセッションストレージを操作したい場合は、Window.sessionStorage メソッドを呼び出してください。ドメインのローカルストレージを操作したい場合は、Window.localStorage を呼び出してください。
プロパティ
- Storage.length読取専用
- 
Storageオブジェクトに保存されているデータアイテムの数を表す整数を返します。
メソッド
- Storage.key()
- 
数値 n を渡すと、ストレージ内で n 番目のキーの名称を返します。 
- Storage.getItem()
- 
キーの名称を渡すと、キーに対する値を返します。 
- Storage.setItem()
- 
キーの名称と値を渡すと、ストレージにキーを追加し、または既存のキーに対する値を更新します。 
- Storage.removeItem()
- 
キーの名称を渡すと、ストレージからキーを削除します。 
- Storage.clear()
- 
ストレージからすべてのキーを消去します。 
例
ここでは、localStorage を呼び出して Storage オブジェクトにアクセスしています。始めに !localStorage.getItem('bgcolor') というコードを使用して、ローカルストレージにデータアイテムが含まれているかを確認します。含まれている場合は、Storage.getItem() を使用してデータアイテムを取得して、さらにそのデータを使用してページのスタイルを更新する setStyles() 関数を実行します。含まれていない場合は populateStorage() 関数を実行します。こちらは Storage.setItem() を使用してアイテムの値を設定してから、setStyles() 関数を実行します。
if (!localStorage.getItem("bgcolor")) {
  populateStorage();
} else {
  setStyles();
}
function populateStorage() {
  localStorage.setItem("bgcolor", document.getElementById("bgcolor").value);
  localStorage.setItem("font", document.getElementById("font").value);
  localStorage.setItem("image", document.getElementById("image").value);
  setStyles();
}
function setStyles() {
  const currentColor = localStorage.getItem("bgcolor");
  const currentFont = localStorage.getItem("font");
  const currentImage = localStorage.getItem("image");
  document.getElementById("bgcolor").value = currentColor;
  document.getElementById("font").value = currentFont;
  document.getElementById("image").value = currentImage;
  htmlElem.style.backgroundColor = `#${currentColor}`;
  pElem.style.fontFamily = currentFont;
  imgElem.setAttribute("src", currentImage);
}
メモ: 完全に動作する例として実行する様子を見るために、Web Storage Demo をご覧ください。
仕様書
| Specification | 
|---|
| HTML> # storage> | 
ブラウザーの互換性
Loading…