๐พ Chrome Extension Storage API: Saving and Retrieving Data
The Chrome Extension Storage API provides a way to store, retrieve, and track changes to user data. Here's how to use it efficiently in your extension.
โ What is the Chrome Extension Storage API?
The Storage API offers two primary options:
chrome.storage.sync
: Syncs data across devices where the user is logged inchrome.storage.local
: Stores data locally on the current device
๐ New to extensions? Start with our Getting Started Guide.
๐ ๏ธ Using the Storage API
1. Request Permission
In your manifest.json
, add:
{
"permissions": ["storage"]
}
2. Saving Data
chrome.storage.sync.set({key: value}, function() {
console.log('Value is set to ' + value);
});
3. Retrieving Data
chrome.storage.sync.get(['key'], function(result) {
console.log('Value currently is ' + result.key);
});
4. Listening for Changes
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (let [key, { oldValue, newValue }] of Object.entries(changes)) {
console.log(
`Storage key "${key}" in namespace "${namespace}" changed.`,
`Old value was "${oldValue}", new value is "${newValue}".`
);
}
});
๐ Storage Limits
chrome.storage.sync
:
- Total: 100KB
- Per item: 8KB
- Max items: 512
chrome.storage.local
:
- Total: ~10MB
- Per item: 5MB
- Unlimited items
For larger datasets, use chrome.storage.local
or IndexedDB.
โ Best Practices
- Use
sync
for user settings or small data - Use
local
for larger datasets - Watch for quota limits
- Handle edge cases and potential errors
๐ Using Storage Across Contexts
You can use the Storage API in:
- Background scripts: for global state
- Content scripts: for page-specific data
- Popup scripts: for transient UI data
- Options pages: for user preferences
๐ Making API Calls with Stored Data
Store and reuse API keys, user preferences, and session info when calling external APIs. Check our API Call Guide for more on this.
๐งพ Conclusion
The Chrome Extension Storage API is a must-know for managing data inside your extension. Youโve learned how to:
- Save and retrieve data
- Listen for storage changes
- Handle limits and best practices
Apply this knowledge to create faster, smarter, and more user-friendly extensions.
Happy building from the Mellowtel Team! ๐