Home

Awesome

webext-storage

A more usable typed storage API for Web Extensions

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:

Native API

const storage = await chrome.storage.local.get('user-options');
const value = storage['user-options']; // The type is `any`
await chrome.storage.local.set({['user-options']: {color: 'red'}}); // Not type-checked
chrome.storage.onChanged.addListener((storageArea, change) => {
	if (storageArea === 'local' && change['user-options']) { // Repetitive
		console.log('New options', change['user-options'].newValue)
	}
});

This API

const options = new StorageItem<Record<string, string>>('user-options');
const value = await options.get(); // The type is `Record<string, string> | undefined`
await options.set({color: 'red'}) // Type-checked
options.onChanged(newValue => {
	console.log('New options', newValue)
});

Why this is better:

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')
// Or
const username = new StorageItem('username', {defaultValue: 'admin'})

await username.set('Ugo');
// Promise<void>

await username.get();
// Promise<string>

await username.remove();
// Promise<void>

await username.set({name: 'Ugo'});
// TypeScript Error: Argument of type '{ name: string; }' is not assignable to parameter of type 'string'.

username.onChanged(newName => {
	console.log('The user’s new name is', newName);
});

Related

License

MIT © Federico Brigante