GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • MDN
  • HTML: Markup language
  • Elements
  • Global attributes
  • Attributes
  • See all…
  • Responsive images
  • HTML cheatsheet
  • Date & time formats
  • See all…
  • SVG
  • MathML
  • XML
  • CSS: Styling language

This view

  • Original page
  • New address

GeezerVison is showing developer.mozilla.org — Storage - Web API | MDN

このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

Storage

Baseline
広く利用可能

この機能は広く実装されており、多くのバージョンの端末やブラウザーで動作します。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() 関数を実行します。

js
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 をご覧ください。

仕様書

仕様書
HTML
# storage

ブラウザーの互換性

関連情報

  • ウェブストレージ API の使用
  • Window.localStorage
  • Window.sessionStorage
  • CacheStorage

MDN の改良に協力

協力方法を知る

このページは 2024年7月28日 に MDN の貢献者によって最終更新されました。

GitHub でこのページを表示 • このコンテンツに関する問題を報告
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.