クライアントサイドデータベースストレージのためのIndexedDBサポート

ブラウザに大量の構造化データを保存するためのIndexedDBサポートを検出。データベース操作、トランザクション、ストレージクォータを解説。

Storage

詳細な説明

IndexedDB検出

IndexedDBは、ファイルやBlobを含む大量の構造化データのクライアントサイドストレージのための低レベルAPIです。Webアプリケーションのオフラインデータストレージの主要な選択肢です。

検出

const hasIndexedDB = typeof indexedDB !== 'undefined';

データベースを開く

function openDB(name, version) {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open(name, version);

    request.onupgradeneeded = (event) => {
      const db = event.target.result;
      if (!db.objectStoreNames.contains('items')) {
        const store = db.createObjectStore('items', {
          keyPath: 'id',
          autoIncrement: true,
        });
        store.createIndex('name', 'name', { unique: false });
      }
    };

    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

CRUD操作

async function addItem(db, item) {
  const tx = db.transaction('items', 'readwrite');
  tx.objectStore('items').add(item);
  return new Promise((resolve, reject) => {
    tx.oncomplete = resolve;
    tx.onerror = () => reject(tx.error);
  });
}

async function getItem(db, id) {
  const tx = db.transaction('items', 'readonly');
  const request = tx.objectStore('items').get(id);
  return new Promise((resolve) => {
    request.onsuccess = () => resolve(request.result);
  });
}

ストレージ比較

ストレージ 容量 同期/非同期 構造化 インデックス
localStorage ~5MB 同期 いいえ(文字列) いいえ
sessionStorage ~5MB 同期 いいえ(文字列) いいえ
IndexedDB ディスクの50%+ 非同期 はい はい
Cache API ディスクの50%+ 非同期 HTTPレスポンス URL別

ストレージクォータ

if (navigator.storage && navigator.storage.estimate) {
  const { usage, quota } = await navigator.storage.estimate();
  console.log(\`\${quota}バイト中\${usage}バイト使用中\`);
}

ブラウザは通常、利用可能なディスク容量の50%以上を許可します。重要なデータの退去を防ぐにはnavigator.storage.persist()を使用してください。

ユースケース

オフラインファーストアプリケーション、APIレスポンスのクライアントサイドキャッシング、同期前のユーザー生成コンテンツの保存、大規模データセット(メールクライアント、ノートアプリなど)の管理、セッション間のアプリケーション状態の永続化を駆動します。

試してみる — Browser Feature Detector

フルツールを開く