Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Svelte stores that are synchronized with extension/browser storage.

License

NotificationsYou must be signed in to change notification settings

ChrRubin/svelte-webext-stores

Repository files navigation

Svelte stores that are synchronized with extension storage.

Note:This library is currently in alpha development, and is subject to breaking changes with or without warning.

Features

  • Different storage types support:chrome.storage (either MV2 or MV3),browser.storage (includingwebextension-polyfill), and even non-extension storage such aswindow.localStorage andwindow.sessionStorage are supported out of the box.
  • Automatically synchronizes to and from storage backend.
  • TypeScript support: This library is fully written in TypeScript, and the distributed package includes TypeScript declarations.
  • Custom implementations: Create and use your own custom storage backends or synchronized stores by implementingIStorageBackend orISyncStore respectively.

Getting started

Installation

npm install -D svelte-webext-stores

or

yarn add -D svelte-webext-stores

Quick Usage

storage.js

import{webExtStores}from'svelte-webext-stores';// Instantiate default store handler, which is backed by MV2 chrome.storage.localconststores=webExtStores();// Register a new synchronized store with storage key 'count' and default value of 1exportconstcount=stores.addSyncStore('count',1);

App.svelte

<script>import{count}from'./storage.js';functionaddCount(){$count+=1;}</script><buttonon:click={addCount}>Count: {$count}</button>

Advanced Usage

Storage Backends

This library supports and exports the following storage options out of the box. To use a provided storage option, simply import it and pass it intowebExtStores.

StorageDescription
storageMV2Chrome Manifest Version 2 (callback API).
storageMV3Chrome Manifest Version 3 (Promise API).
storageWebExtMozilla WebExtension (browser API), includingwebextension-polyfill.
storageLegacyLegacy/non-extension storage (localStorage orsessionStorage).

To set the storage area/type, pass the corresponding string parameter.

StorageAllowed parameterDefault
storageMV2,storageMV3,storageWebExt'local' |'sync' |'managed''local'
storageLegacy'session' |'local''session'

Example:

import{webExtStores,storageWebExt}from'svelte-webext-stores';// Uses the Mozilla WebExtension browser API in the 'sync' area.conststores=webExtStores(storageWebExt('sync'));

More information on theIStorageBackend interface that is implemented by all the above storage backends can be foundhere.

Synchronized Stores

All provided synchronized stores below implements theISyncStore interface. More information can be foundhere.

SyncStore

Standard store that synchronizes to the storage backend. Uses Sveltewritable to implement the Svelte store contract.

WebExtStores.addSyncStore<T>(key:string,defaultValue:T,syncFromExternal=true,versionedOptions?:VersionedOptions):SyncStore<T>
ParameterDescription
keyStorage key
defaultValueStore's default value
syncFromExternalWhether store should be updated when storage value is updated externally
versionedOptionsEnables options for migrating storage values from an older version to a newer version

Aside from methods derived fromISyncStore,SyncStore also contains the following methods:

MethodsSignatureDescription
readyready: () => Promise<void>Ensure that any async initialization process (such as initial update from backend) has been completed. You typically don't need to manually call this unless you wish to sync the store to the storage backend before any ofget(),set(),subscribe() orupdate() is called.
resetreset: () => Promise<void>Reset store value to default value.
updateupdate: (updater: (value: T) => T) => Promise<void>Update value using callback and inform subscribers.

LookupStore

Synchronized store forRecord<string, any> objects.LookupStore is derived from and is functionally similar toSyncStore, with additional convenience methods for getting and setting the stored object's property values using property keys.

WebExtStores.addLookupStore<TextendsRecord<string,any>>(key:string,defaultValue:T,syncFromExternal=true,versionedOptions?:VersionedOptions<T>):LookupStore<T>
MethodsSignatureDescription
getItemgetItem: <R extends T[keyof T]>(key: keyof T) => Promise<R>Get property value.
setItemsetItem: <V extends T[keyof T]>(key: keyof T, value: V) => Promise<void>Set property value.

Example:

import{webExtStores}from'svelte-webext-stores';conststores=webExtStores();exportconstobj=stores.addLookupStore('obj',{a:1,b:false,c:'3'});consta=awaitobj.getItem('a');// Returns 1awaitobj.setItem('b',true);// Object is now { a: 1, b: false, c: '3' }

You can also easily add these convenience methods to your customISyncStore implementations. More information can be foundhere.

Versioned Store Values and Migration

SyncStore and its derivatives has the optional parameterversionedOptions. When the parameter is provided, it keeps track of the current store's version to enable ease of migrating values from an older store version to the current version. This can be useful to migrate breaking changes on the stored data without reseting its value to default.

VersionedOptions properties are as follows:

PropertyTypeDescrption
versionnumberCurrent version number. Do not use-1.
seperatorstringSeparator between key and version.
migrationsMap<number, (oldValue: any) => T>Map for migrating values. Keys are the old version to match against, and values are callbacks that accepts the value found from the given old version and returns the corresponding value for the current version. Use the key-1 to migrate from a versionless store.

SyncStores that are provided with theversionedOptions parameter are stored as${key}${seperator}${version} internally. When an older version that matches any of the keys in the Map is found, its value is passed to the callback, the returned value is stored and the old version is removed.

// Initial storeexportconstsize=stores.addSyncStore('size',500);// Example usage in sveltewindow.resizeTo($size,$size);
// To migrate to a new value, replace the old declarationconstsizeMigrations=newMap();sizeMigrations.set(-1,(oldValue)=>`${oldValue}x${oldValue*2}`);exportconstsize=stores.addSyncStore('size','500x1000',true,{version:1,seperator:'$',migrations:sizeMigrations});// Example usage in svelteconst[width,height]=$size.split('x');window.resizeTo(width,height);

About

Svelte stores that are synchronized with extension/browser storage.

Topics

Resources

License

Stars

Watchers

Forks

Contributors3

  •  
  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp