🚀 Big News: Socket Acquires Coana to Bring Reachability Analysis to Every Appsec Team.Learn more

webext-storage

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

webext-storage

A more usable typed storage API for Web Extensions

2.0.1
latest
Version published
Weekly downloads
4K
80.21%
Maintainers
0
Weekly downloads
 
Created

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's not type-safe. This module provides a better API:

Comparison 💥
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)
});
  • The storage item is defined in a single place, including its storageArea, its types and default value
  • item.get() returns the raw value instead of an object
  • Every get and set operation is type-safe
  • If you provide a defaultValue, the return type will not be | undefined
  • Calling .set(undefined) will unset the value instead of the call being ignored
  • The onChanged example speaks for itself

Now compare it to the 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)
	}
});

Install

npm install webext-storage

Or download the standalone bundle to include in your manifest.json.

Usage

The package exports two classes:

  • StorageItem - Store a single value in storage
  • StorageItemMap - Store multiple related values in storage with the same type, similar to new Map()

Support:

  • Browsers: Chrome, Firefox, and Safari
  • Manifest: v2 and v3
  • Permissions: storage or unlimitedStorage
  • Context: They can be called from any context

License

MIT © Federico Brigante

FAQs

Package last updated on 17 Mar 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts