Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including svelte-webext-storage-adapter with all npm packages installed. Try it out:

svelte-webext-storage-adapter lists no main file and has no index.js, so it can't be directly required. If this is a mistake, please let us know. It may however contain internal files that you can require manually:

require("svelte/package.json"); // svelte is a peer dependency. // require("svelte-webext-storage-adapter/[??]")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

svelte-webext-storage-adapter v1.0.0

Svelte stores, backed up by chrome.storage

svelte-webext-storage-adapter

If you're using Svelte v3 to make a WebExtension for Firefox or Chrome, you can use this to create writable stores that are backed by your extension's storage. Handy features are provided to you right out of the box:

  • Flexible: This package can work with a part of or the entirety of any area of chrome.storage, including areas from 3rd-party packages.
  • Automatic batching: Save on storage writes when all your store changes are batched up to be sent out at the next Svelte tick.
  • Live updates: If you'd like, this package will handle listening for storage changes for you.

This project has a Code of Conduct. By participating in the Git repo or issues tracker, you agree to be as courteous, welcoming, and generally a lovely person as its terms require. 😊

Default export: webextStorageAdapter()

Parameters: keys (string, array, object, or null), optional options (object)
Returns a store group

Creates a group of Svelte v3 writable stores, populated from & persisted to chrome.storage (by default, the sync area). It will immediately request the needed values; this is asynchronous, but the store group will be returned synchronously with all stores in place. You can use the store group's ready promise to determine when values from storage are available.

// Example

import webextStorageAdapter from "svelte-webext-storage-adapter";
var storeGroup = webextStorageAdapter(["thisKey", "thatKey"]);
storeGroup.ready.then( () => {
    // You can now interact with data in storage
} );

Parameter: keys

string, array, object, or null

This can be any of the same values accepted by StorageArea.get. Using null will allow the store group to read and write any key in storage. Unlike StorageArea.get, default values specified in the object form are guaranteed to survive the round trip.

// Example: Specifying keys with default values
var storeGroup = webextStorageAdapter({
    i: "he",
    you: "me",
    we: "all together",
});
storeGroup.stores.we.subscribe(console.log); // logs "all together"

Parameter: options

object

An optional parameter with optional properties storageArea, live, and onSetError, the effects of which are detailed below.

storageArea

StorageArea
Default: chrome.storage.sync

The area that will be read from and written to, usually either chrome.storage.sync or chrome.storage.local.

// Example: Making store groups for both local and sync
var localGroup = webextStorageAdapter(null, {storageArea: chrome.storage.local});
var syncGroup = webextStorageAdapter(null);
Using external storage areas

It's possible to use StorageArea objects not originally part of chrome.storage, such as the chrome-storage-largeSync package (not linking as it seems to be unmaintained as of this writing).

Implementors of such objects must provide get and set methods compatible with Chrome's implementation (this package does not support Promise-using versions of those methods). For the live option below to work, they must also implement the onChanged property introduced in Chrome 73. They may indicate errors either by setting chrome.runtime.lastError (⚠️ but they need to delete it afterwards), or by passing an extra parameter to the callbacks.

live

boolean
Default: true

If true, webextStorageAdapter will attempt to listen for changes to options.storageArea and propagate them to the stores. If a key is deleted from storage, this will set the key's corresponding store to its default value if one was specified in the keys parameter, or undefined otherwise.

This will prevent the store group from being garbage-collected. If this is a concern, you can call the group's unLive method when you're done with it.

webextStorageAdapter supports both options.storageArea.onChanged and chrome.storage.onChanged.

// Example

// In your extension's tab page / browser action popup / etc.
import webextStorageAdapter from "svelte-webext-storage-adapter";
// The live option defaults to true, but we explicitly set it here for demonstration purposes
var storeGroup = webextStorageAdapter("noise", {live: true});
storeGroup.stores.noise.subscribe( (value) => console.log(value) );
chrome.runtime.sendMessage("Sound the alarm!");

// In your extension's background page
chrome.runtime.onMessage.addListener( (message) => {
    if (message == "Sound the alarm!") {
        chrome.storage.sync.set({noise: "awooga"}); // The above script will eventually log "awooga"
    }
} );

onSetError()

Called with: error (object), setItems (object)
Default: (error, setItems) => { console.error("error: ", error, "\n", "setItems: ", setItems); }

If an attempt to write to options.storageArea fails, this function is called with error as the error that was reported and setItems as the first parameter given to options.storageArea.set. Note that changes to the stores will not be rolled back.

Returned value: Store group

Object

Provides access to the requested stores, plus properties that concern all of them as a whole.

Property: stores

Object (prototype: null)

This has a property for every key specified in webextStorageAdapter's keys parameter, and each property's value is a Svelte writable store containing the corresponding value in options.storageArea. If keys was null, then stores is a Proxy that allows getting any property to obtain a usable store, but operations such as Object.keys(), for...in, etc. will only expose keys that are known to have values.

New values introduced via the stores' set and update methods are batched up into a single options.storageArea.set() call that happens when Svelte's tick() resolves. The stores themselves will have their new values immediately.

To help avoid bugs in your code, directly setting any property of stores is disallowed, and will throw an error in strict mode. Remember to use stores.example.set(value) instead of stores.example = value!

// Example

import webextStorageAdapter from "svelte-webext-storage-adapter";
var storeGroup = webextStorageAdapter(null);
// Since storeGroup.ready hasn't resolved yet, no data will be loaded...
console.log( Object.keys(storeGroup.stores) ); // []
// ... but we can set data and have it sent to extension storage anyways
storeGroup.stores.tooBad.set("Waluigi time");
console.log( Object.keys(storeGroup.stores) ); // ["tooBad"]

// For non-null keys parameters, the specified keys are always present
var storeGroup2 = webextStorageAdapter(["thing1", "thing2"]);
console.log( Object.keys(storeGroup2.stores) ); // ["thing1", "thing2"]
⚠️ Caution: When keys == null, unused stores may be invalidated

When all of the following are true for a given property of stores...

  • null was passed as the keys parameter to webextStorageAdapter
  • There is no known value for the property's store, whether set directly or obtained from options.storageArea
  • There are no subscribers for the property's store

... then every read of that property will result in a different store. When one such store's get, update, or subscribe is used, all others will be invalidated. If all the above conditions are still true when a value arrives from options.storageArea, all existing stores will be invalidated! (The next read will provide a valid store.) When a store is invalidated, all of its methods will throw an error.

The best way to avoid invalid stores is to subscribe to one as soon as you get it. Auto-subscriptions are a great way to do this inside a Svelte component.

Property: ready

Promise

Resolves with true after all stores have been set to values received from the initial options.storageArea.get call, or rejects with a reported error object.

// Example

// In a Svelte component's <script> block
import webextStorageAdapter from "svelte-webext-storage-adapter";
var { stores, ready, unLive } = webextStorageAdapter(null);
var preparations = Promise.all([ready, ...otherAsyncWork]);
<!-- In the same component's markup -->
{#await preparations}
    <LoadingAnimation/>
{:then}
    <UsefulContent/>
{/await}

Property: unLive()

No parameters

Reverses the effects of the live: true option so that the store group can be garbage-collected. This function does not use this and may be freely reassigned.

// Example

// In a Svelte component's <script> block
import webextStorageAdapter from "svelte-webext-storage-adapter";
import { onDestroy } from "svelte";

var { stores, ready, unLive } = webextStorageAdapter("myKey");
onDestroy( () => {
    unLive();
} );

Suggested usage: Dedicated module

I recommend having a module in your project specifically for calling webextStorageAdapter, like so:

// In file storage.esm.js
import webextStorageAdapter from "svelte-webext-storage-adapter";

var {stores, ready} = webextStorageAdapter({
    "Your": "default",
    "values": "default",
    "here": "default",
}, {
    onSetError(error, setItems) {
        // Your error-handling logic here
    }
})
export { stores, ready, stores as default };

// In a component's script
import storage from "./storage.esm.js";

var {here} = storage;
$: reactToHere( $here );

Tip: Use with svelte-writable-derived

Full disclosure: I, Pikadude, am the author of svelte-writable-derived. If you find this tip helpful, now you have two reasons to support me!

Chrome's implementation of chrome.storage can't safely store anything besides booleans, numbers, strings, and arrays. If you need something more complex, you can use the svelte-writable-derived package to translate your data to & from its storage-safe form.

import webextStorageAdapter from "svelte-webext-storage-adapter";
import writableDerived from "svelte-writable-derived";

var {stores, ready} = webextStorageAdapter({
    "key": `{"storedAsJson":true}`,
})
exportedStores = Object.assign({}, stores, {
    "key": writableDerived(
        stores.key,
        (json) => JSON.parse(json),
        ({reflecting}) => JSON.stringify(reflecting)
    ),
});
export { exportedStores as stores, ready, exportedStores as default };

Browser compatibility

This package supports any version of Firefox or Chrome with support for chrome.runtime, chrome.storage, and ECMAScript 6th Edition. If webextStorageAdapter(null) is not used, transpilers and polyfills may be used to fill in for missing ECMAScript 6 support.

💖 Support the developer

I muchly appreciate any way you'd like to show your thanks - knowing people are helped gives me warm fuzzies and makes it all worthwhile!

💸 ... with money

I'm on Ko-Fi! If you'd like to make a recurring donation, first please help me afford Ko-Fi Gold!

💌 ... with kind words

Current contact info is on this page - or you can create an "issue" on this repo just to say thanks! Thank-you "issues" will be closed right away, but are treasured regardless~

🤝 ... with a job

I have a Developer Story on Stack Overflow!

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free