webext-storage
A more usable typed storage API for Web Extensions
- Browsers: Chrome, Firefox, and Safari
- Manifest: v2 and v3
- Permissions:
storage
or unlimitedStorage
- Context: They can be called from any context
Sponsored by PixieBrix :tada:
chrome.storage.local.get()
is very inconvenient to use and it does not provide type safety. This module provides a better API:
const storage = await chrome.storage.local.get('user-options');
const value = storage['user-options'];
await chrome.storage.local.set({['user-options']: {color: 'red'}});
chrome.storage.onChanged.addListener((storageArea, change) => {
if (storageArea === 'local' && change['user-options']) {
console.log('New options', change['user-options'].newValue)
}
});
const options = new StorageItem<Record<string, string>>('user-options');
const value = await options.get();
await options.set({color: 'red'})
options.onChanged(newValue => {
console.log('New options', newValue)
});
Why this is better:
- The storage item is defined in a single place, including its storageArea, its types and default value
get
only is only .get()
instead of the awkward post-get object access that- Every
get
and set
operation is type-safe - If you provide a
defaultValue
, the return type will not be | undefined
- The
onChanged
example speaks for itself
Install
npm install webext-storage
Or download the standalone bundle to include in your manifest.json
.
Usage
import {StorageItem} from "webext-storage";
const username = new StorageItem<string>('username')
const username = new StorageItem('username', {defaultValue: 'admin'})
await username.set('Ugo');
await username.get();
await username.remove();
await username.set({name: 'Ugo'});
username.onChanged(newName => {
console.log('The user’s new name is', newName);
});
Related
License
MIT © Federico Brigante