All Projects → PixievoltNo1 → svelte-webext-storage-adapter

PixievoltNo1 / svelte-webext-storage-adapter

Licence: MIT license
Svelte stores, backed up by chrome.storage

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to svelte-webext-storage-adapter

perfect-home
firefox newtab/home replacement
Stars: ✭ 101 (+461.11%)
Mutual labels:  webextension, firefox-extension, svelte3
Disable Javascript
Adds the ability to disable JavaScript on specific sites.
Stars: ✭ 151 (+738.89%)
Mutual labels:  webextension, firefox-extension
RegexSearch
Firefox Extension (WebExtension) to Search in HTML using Regular Expression (REGEX)
Stars: ✭ 38 (+111.11%)
Mutual labels:  webextension, firefox-extension
Floccus
☁️ Sync your bookmarks privately across browsers
Stars: ✭ 2,630 (+14511.11%)
Mutual labels:  webextension, firefox-extension
Livemarks
Extension that restores RSS Feed Livemarks in Firefox.
Stars: ✭ 137 (+661.11%)
Mutual labels:  webextension, firefox-extension
Vivaldi Fox
An add-on that aims to add Vivaldi style toolbar colouring to the Firefox UI
Stars: ✭ 149 (+727.78%)
Mutual labels:  webextension, firefox-extension
Github Mermaid Extension
A browser extension for Chrome, Opera & Firefox that adds Mermaid language support to Github
Stars: ✭ 170 (+844.44%)
Mutual labels:  webextension, firefox-extension
Fx cast
Implementation of the Google Cast Chrome Sender SDK within Firefox
Stars: ✭ 1,319 (+7227.78%)
Mutual labels:  webextension, firefox-extension
Archiveror
Archiveror will help you preserve the webpages you love. 💾
Stars: ✭ 246 (+1266.67%)
Mutual labels:  webextension, firefox-extension
enterprise-policy-generator
The Enterprise Policy Engine allows administrators to configure Firefox via a configuration file. The Enterprise Policy Generator helps to create the configuration file.
Stars: ✭ 57 (+216.67%)
Mutual labels:  webextension, firefox-extension
quickjira
🚤 📂 Quickly access the JIRA of your choice by typing the ticket id
Stars: ✭ 65 (+261.11%)
Mutual labels:  webextension, firefox-extension
Newtaboverride
New Tab Override allows you to set the page that shows whenever you open a new tab.
Stars: ✭ 120 (+566.67%)
Mutual labels:  webextension, firefox-extension
Html5 Video Everywhere
Higher performance and stable video watching experience on the web
Stars: ✭ 118 (+555.56%)
Mutual labels:  webextension, firefox-extension
Ff2mpv
A Firefox add-on for playing URLs in mpv.
Stars: ✭ 149 (+727.78%)
Mutual labels:  webextension, firefox-extension
Save In
WebExtension for saving media, links, or selections into user-defined directories
Stars: ✭ 99 (+450%)
Mutual labels:  webextension, firefox-extension
Absolutedoubletrace
A web extension to block browser fingerprinting
Stars: ✭ 156 (+766.67%)
Mutual labels:  webextension, firefox-extension
FireX-Proxy
FireX Proxy for Mozilla Firefox, Google Chrome
Stars: ✭ 96 (+433.33%)
Mutual labels:  webextension, firefox-extension
Universal Bypass
Don't waste your time with compliance. Universal Bypass circumvents annoying link shorteners.
Stars: ✭ 1,287 (+7050%)
Mutual labels:  webextension, firefox-extension
Bookmarks Organizer
With the Bookmarks Organizer it's easy to put order in your bookmarks. The Bookmarks Organizer finds no longer working bookmarks, redirects, duplicates and more!
Stars: ✭ 90 (+400%)
Mutual labels:  webextension, firefox-extension
Privacybadger
Privacy Badger is a browser extension that automatically learns to block invisible trackers.
Stars: ✭ 2,346 (+12933.33%)
Mutual labels:  webextension, firefox-extension

svelte-webext-storage-adapter

npm Bundle size License

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, using the modern StorageArea.onChanged event that 3rd-party areas can use, and falling back on chrome.storage.onChanged if needed.

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. 😊

👀 Version 3 is in planning! Leave your feedback and help it be the best version yet!

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 will survive the round trip regardless of type.

// 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 StorageArea's get and set methods, accepting callbacks. For the live option below to work, they must also implement the onChanged property. 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 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.

This throws an error if used with a 3rd-party area that doesn't support it.

// 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"]

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, Pixievolt, 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),
		(data) => JSON.stringify(data)
	),
});
export { exportedStores as stores, ready, exportedStores as default };

Browser compatibility

This package officially supports Firefox and Chrome. Other browsers with the chrome.storage and chrome.runtime APIs aren't tested, but bug reports and pull requests for them are welcome.

If you don't use webextStorageAdapter(null), support for ECMAScript 6th Edition is required, but transpilers and polyfills may be used. If you do use webextStorageAdapter(null), support for WeakRef and FinalizationRegistry are required, and transpilers/polyfills are not supported.

💖 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

You can make a one-time donation or become an ongoing sponsor at my Sponsus page, and sponsors can ask me to prioritize development of this package.

💌 ... 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!

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].