Storage API
Storage API
Section titled “Storage API”Chrome Storage APIは、拡張機能のデータを永続化するためのAPIです。
Storage APIの種類
Section titled “Storage APIの種類”1. chrome.storage.local
Section titled “1. chrome.storage.local”// データの保存chrome.storage.local.set({ key: 'value' }, () => { console.log('Data saved');});
// データの取得chrome.storage.local.get(['key'], (result) => { console.log('Value:', result.key);});
// すべてのデータを取得chrome.storage.local.get(null, (result) => { console.log('All data:', result);});
// データの削除chrome.storage.local.remove(['key'], () => { console.log('Data removed');});
// すべてのデータを削除chrome.storage.local.clear(() => { console.log('All data cleared');});2. chrome.storage.sync
Section titled “2. chrome.storage.sync”// ユーザーのChromeアカウント間で同期chrome.storage.sync.set({ settings: { theme: 'dark' } }, () => { console.log('Settings synced');});
// 変更の監視chrome.storage.onChanged.addListener((changes, areaName) => { if (areaName === 'sync' && changes.settings) { console.log('Settings changed:', changes.settings.newValue); }});高度な使用例
Section titled “高度な使用例”1. データのバッチ操作
Section titled “1. データのバッチ操作”// 複数のキーを一度に操作chrome.storage.local.set({ user: { name: 'John', email: 'john@example.com' }, settings: { theme: 'dark', language: 'ja' }, cache: { timestamp: Date.now(), data: [] }}, () => { console.log('Batch save completed');});2. ストレージのクォータ管理
Section titled “2. ストレージのクォータ管理”// ストレージ使用量の確認chrome.storage.local.getBytesInUse(null, (bytesInUse) => { const quota = chrome.storage.local.QUOTA_BYTES; const usagePercent = (bytesInUse / quota) * 100; console.log(`Storage usage: ${usagePercent.toFixed(2)}%`);});
// 特定のキーの使用量chrome.storage.local.getBytesInUse(['largeData'], (bytes) => { console.log(`Key usage: ${bytes} bytes`);});3. データの圧縮
Section titled “3. データの圧縮”// 大きなデータを圧縮して保存function compressAndSave(data) { const jsonString = JSON.stringify(data); const compressed = LZString.compress(jsonString);
chrome.storage.local.set({ compressedData: compressed }, () => { console.log('Compressed data saved'); });}
// データの展開function loadAndDecompress() { chrome.storage.local.get(['compressedData'], (result) => { if (result.compressedData) { const decompressed = LZString.decompress(result.compressedData); const data = JSON.parse(decompressed); console.log('Decompressed data:', data); } });}ストレージイベントの監視
Section titled “ストレージイベントの監視”// ストレージ変更の監視chrome.storage.onChanged.addListener((changes, areaName) => { for (let key in changes) { const change = changes[key]; console.log(`Key "${key}" changed:`); console.log(' Old value:', change.oldValue); console.log(' New value:', change.newValue); }});
// 特定のキーのみ監視chrome.storage.onChanged.addListener((changes, areaName) => { if (changes.user) { console.log('User data changed'); }});