@extend-chrome/storage

中文文档
1.5.0发布于 2021/06/28MITTypeScriptESM + CJS近 30 天下载 3004

This is a wrapper for the Chrome Extension Storage API that adds promises and functional set transactions similar to the React this.setState API. Functional set transactions make it easy to use the Chrome Storage API to share and manage state between di

原始使用文档
文档目录14 节
  1. @extend-chrome/storage
  2. Installation
  3. Virtual typed storage buckets
  4. Promises and functional setters
  5. Composed set operations
  6. interface Bucket
  7. async function bucket.get
  8. async function bucket.getKeys
  9. async function bucket.set
  10. async function bucket.remove
  11. async function bucket.clear
  12. async function bucket.changeStream
  13. async function bucket.valueStream
  14. function getBucket

@extend-chrome/storage logo

@extend-chrome/storage

npm (scoped) GitHub last commit License TypeScript Declarations Included

Fiverr: We make Chrome extensions ko-fi


Manage Chrome Extension storage easily with @extend-chrome/storage.

This is a wrapper for the Chrome Extension Storage API that adds great TypeScript support using virtual storage buckets with a modern Promise-based API.

Table of Contents

Getting started

You will need to use a bundler like Rollup, Parcel, or Webpack to include this library in your Chrome extension.

See rollup-plugin-chrome-extension for an easy way to use Rollup to build your Chrome extension!

Installation

npm i @extend-chrome/storage

Usage

Add the storage permission to your manifest.json file.

// manifest.json
{
  "permissions": ["storage"]
}

Take your Chrome extension to another level! 🚀

import { storage } from '@extend-chrome/storage'

// Set storage using an object
storage.set({ friends: ['Jack'] })

// Set storage using a function
storage.set(({ friends }) => {
  // friends is ['Jack']
  return { friends: [...friends, 'Amy'] }
})

// Get storage value using a key
storage.get('friends').then(({ friends }) => {
  // friends is ['Jack', 'Amy']
})

// Get storage values using an object
storage
  .get({ friends: [], enemies: [] })
  .then(({ friends, enemies }) => {
    // friends is ['Jack', 'Amy']
    // enemies is the [] from the getter object
  })

Features

Virtual typed storage buckets

This library allows you to create a storage area and define the type of data that area will manage.

import { getBucket } from '@extend-chrome/storage'

interface Store {
  a: string
  b: number
}

const store = getBucket<Store>('store')

store.set({ a: 'abc', b })
store.set(({ b = 0 }) => ({ b: b + 500 }))

store.set({ c: true }) // ts error
store.set(({ a }) => ({ d: 'invalid' })) // ts error

Promises and functional setters

The Chrome Storage API is asynchronous. This means synchronous calls to get and set will not reflect pending changes. This makes calls to set that depend on values held in storage difficult.

While the Chrome Storage API is async, it uses callbacks. This brings a whole world of difficulty into the developer experience that have been solved with Promises.

@extend-chrome/storage solves both of these problems. Every method returns a Promise and both get and set can take a function that provides current storage values, similar to React's this.setState.

Composed set operations

The set method can be called with a function (setter) as well as the normal types (a string, array of strings, or an object).

This setter will receive the entire contents of that storage area as an argument. It must return an object which will be passed to the native storage area set method.

Synchronous calls to set will be composed into one call to the native set. The setters will be applied in order, but each call will resolve with the final value passed to the storage area.

bucket.set({ a: 123 })
bucket.set({ b: 456 })
bucket
  .set(({ a, b }) => {
    // a === 123
    // b === 456
    return { c: 789 }
  })
  .then(({ a, b, c }) => {
    // New values in bucket
    // a === 123
    // b === 456
    // c === 789
  })

An individual call to set will reject if the setter function throws an error or returns an invalid type, but will not affect other set operations.

API

interface Bucket

A synthetic storage area. It has the same methods as the native Chrome API StorageArea, but get and set can take a function as an argument. A Bucket can use either local or sync storage.

Multiple synchronous calls to set are composed into one call to the native Chrome API StorageArea.set.

Default storage areas are included, so you can just import storage if you're don't care about types and only need one storage area.

import { storage } from '@extend-chrome/storage'

storage.local.set({ a: 'abc' })
storage.sync.set({ b: 123 })

Create a bucket or two using getBucket:

import { getBucket } from '@extend-chrome/storage'

// Buckets are isomorphic, so export and
// use them throughout your extension
export const bucket1 = getBucket('bucket1')
export const bucket2 = getBucket('bucket2')

Each bucket is separate, so values don't overlap.

bucket1.set({ a: 123 })
bucket2.set({ a: 'abc' })

bucket1.get() // { a: 123 }
bucket2.get() // { a: 'abc' }

Buckets really shine if you're using TypeScript, because you can define the types your bucket will contain. Click here for more details.

async function bucket.get

Takes an optional getter. Resolves to an object with the requested storage area values.

Parameters

function get(getter?: string | object | Function) => Promise<{ [key: string]: any }>

[getter]
Type: null, string, string array, or function
Default: null
Usage is the same as for the native Chrome API, except for the function getter.

  • Use null to get the entire bucket contents.
  • Use a string as a storage area key to get an object with only that key/value pair.
  • Use an object with property names for the storage keys you want.
    • The values for each property will be used if the key is undefined in storage.
  • Use a function to map the contents of storage to any value.
    • The function will receive the entire contents of storage as the first argument.
    • The call to get will resolve to the function's return value.
  • Calls to get after set will resolve to the new set values.

bucket.get('a') // resolves to object as key/value pair
bucket.get({ a: 123 }) // same, but 123 is default value
bucket.get(({ a }) => a) // resolves to value of "a"

async function bucket.getKeys

Takes an optional getter. Resolves to an array of strings that represents the keys of the values in the storage area bucket.

function getKeys() => Promise<string[]>
bucket.set({ a: 123 })
bucket.getKeys() // Resolves to ['a']

async function bucket.set

Set a value or values in storage. Takes a setter object or function. Resolves to the new bucket values.

Parameters

function set(setter: object | Function) => Promise<{ [key: string]: any }>

setter
Type: object or Function

  • Use an object with key/value pairs to set those values to storage.
  • Use a Function that returns an object with key/value pairs.
    • The setter function receives the results of previous synchronous set operations.
    • The setter function cannot be an async function.
  • Returns a Promise that resolves to the new storage values.
  • Calls to get after set will resolve with the new values.
// Values in bucket: { a: 'abc' }

// First call to set
bucket.set({ b: 123 })

// Second synchronous call to set
bucket
  .set(({ a, b, c }) => {
    // Values composed from storage
    // and previous call to set:
    // a === 'abc'
    // b === 123
    // c === undefined
    return { c: true }
  })
  .then(({ a, b, c }) => {
    // New values in storage
    // a === 'abc'
    // b === 123
    // c === true
  })

bucket.set({ a: 123 })
bucket
  .set(({ a }) => ({ b: true }))
  .then(({ a, b }) => {
    // Values were set
    // a === 123
    // b === true
  })

async function bucket.remove

Remove a value or values from storage. Resolves when the operation is complete.

bucket.remove('a')
bucket.remove(['a', 'b'])

async function bucket.clear

Empties only this bucket. Resolves when the operation is complete. Other buckets are untouched.

bucket.clear()

async function bucket.changeStream

An RxJs Observable that emits a StorageChange object when the Chrome Storage API onChanged event fires.

bucket.changeStream
  .pipe(filter(({ a }) => !!a))
  .subscribe(({ a }) => {
    console.log('old value', a.oldValue)
    console.log('new value', a.newValue)
  })

async function bucket.valueStream

An Observable that emits all the values in storage immediately, and when onChanged fires.

bucket.valueStream.subscribe((values) => {
  console.log('Everything in this bucket', values)
})

function getBucket

Create a bucket (a synthetic storage area). Takes a string bucketName and an optional string areaName. Returns a Bucket synthetic storage area. Export this bucket and use it throughout your Chrome extension. It will work everywhere, including privileged pages and content scripts.

getBucket is a TypeScript Generic. Pass it an interface to define the types to expect in your storage area.

Parameters

function getBucket(bucketName: string, areaName?: 'local' | 'sync') => Bucket

bucketName
Type: string
A unique id for this bucket.

[areaName]
Type: "local" or "sync"
Default: "local"
Choose which native Chrome API storage area to use.

import { getBucket } from '@extend-chrome/storage'

// JavaScript
export const localBucket = getBucket('bucket1')
export const syncBucket = getBucket('bucket2', 'sync')

// TypeScript
export const localBucket = getBucket<{ a: string }>('bucket1')
export const syncBucket = getBucket<{ b: number }>(
  'bucket2',
  'sync',
)

版本与发布记录

@extend-chrome/storage 共发布 15 个版本,首次发布于 2020/06/09;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.5.0latest2021/06/285 年前
1.5.0-0beta2021/06/095 年前
1.4.52021/05/265 年前
1.4.5-02021/05/265 年前
1.4.42021/05/265 年前
1.4.32021/01/155 年前

其他发布通道:legacy → 0.2.1,beta → 1.5.0-0。

关于 @extend-chrome/storage 的常见问题

@extend-chrome/storage 是什么?

This is a wrapper for the Chrome Extension Storage API that adds promises and functional set transactions similar to the React this.setState API. Functional set transactions make it easy to use the Chrome Storage API to share and manage state between di

如何安装 @extend-chrome/storage?

在项目目录运行 npm install @extend-chrome/storage,或使用 pnpm add / yarn add / bun add。

@extend-chrome/storage 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@extend-chrome/storage 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@extend-chrome/storage 可以商用吗?

@extend-chrome/storage 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@extend-chrome/storage 的下载量有多少?

根据 npm 官方下载统计,@extend-chrome/storage 在 2026/10/14 – 2026/11/12 这 30 天内被下载 3,004 次,日均约 100 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@extend-chrome/storage 还在维护吗?

最新版本 1.5.0 发布于 2021/06/28(5 年前);至今共发布 15 个版本,其中过去 12 个月发布了 0 个;首次发布于 2020/06/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。