localStorage reliably across all extension contexts. Use the chrome.storage API instead — it works in content scripts, the background service worker, the popup, and the options page.
Sync vs local storage
Choose the right storage area based on how the data should behave:Write data
Callchrome.storage.sync.set or chrome.storage.local.set with an object of key-value pairs:
- sync
- local
Read data
Pass an array of keys to retrieve:- sync
- local
null to read everything in storage:
Remove and clear data
React to storage changes
Listen for changes across all extension contexts usingchrome.storage.onChanged. This is useful for keeping the popup and content scripts in sync without manual polling:
Full example: save and load user preferences
Prompt Extensy to use storage
Include storage requirements in your extension prompt:“Remember the user’s preferred language setting across sessions. Let them change it on the options page and apply it in the popup.”Extensy will generate
chrome.storage.sync.set and chrome.storage.sync.get calls in the appropriate files. If you need large-scale caching, specify that explicitly:
“Cache the last 50 search results in chrome.storage.local and clear them when the user clicks ‘Reset cache’.”
chrome.storage is asynchronous. Always read data inside the callback (or use await with the Promise-based API available in MV3) before acting on the result.