An ES6 Map wrapper for the synchronous userscript storage API
npm install gm-storage

- NAME
- FEATURES
- INSTALLATION
- USAGE
- DESCRIPTION
- TYPES
- EXPORTS
- GMStorage (default)
- Constructor
- Options
- strict
- JSONKeyStore
- Constructor
- Options
- canonical
- Methods
- clear
- delete
- entries
- forEach
- get
- has
- keys
- set
- setAll
- values
- Properties
- size
- Symbol.iterator
- DEVELOPMENT
- COMPATIBILITY
- SEE ALSO
- Libraries
- APIs
- VERSION
- AUTHOR
- COPYRIGHT AND LICENSE
gm-storage - an ES6 Map wrapper for the synchronous userscript storage API
- implements the full Map API with some helpful extras
- no dependencies
- < 600 B minified + gzipped
- fully typed (TypeScript)
- CDN builds (UMD) - [jsDelivr][], [unpkg][]
```
$ npm install gm-storage
`javascript
// ==UserScript==
// @name My Userscript
// @include https://www.example.com/*
// @require https://unpkg.com/gm-storage@4.1.1
// @grant GM_deleteValue
// @grant GM_getValue
// @grant GM_listValues
// @grant GM_setValue
// ==/UserScript==
const store = new GMStorage()
// now access userscript storage with the ES6 Map API
store.set('alpha', 'beta') // store
store.set('foo', 'bar').set('baz', 'quux') // store
store.get('foo') // "bar"
store.get('gamma', 'default value') // "default value"
store.delete('alpha') // true
store.size // 2
// iterables
[...store.keys()] // ["foo", "baz"]
[...store.values()] // ["bar", "quux"]
Object.fromEntries(store) // { foo: "bar", baz: "quux" }
`
GMStorage implements an ES6 Map compatible wrapper
(adapter) for the synchronous
userscript storage API.
It augments the built-in API with some useful enhancements such as iterating
over values and entries, and removing all values.
It also adds some features which aren't available in the Map API, e.g.
get takes an optional default value (the same as GM_getValue).
The synchronous storage API is supported by most userscript engines:
- Violentmonkey
- Tampermonkey
- USI
- Greasemonkey 3
The notable exceptions are Greasemonkey 4
and FireMonkey, which have
moved exclusively to the asynchronous API.
The following types are referenced in the descriptions below:
`typescript
type JSONValue =
| null
| boolean
| number
| string
| JSONValue[]
| { [key: string]: JSONValue };
type Callback
this: U | undefined,
value: V,
key: K,
store: GMStorage
) => void;
interface Options {
strict?: boolean;
};
interface JSONKeyStoreOptions extends Options {
canonical?: boolean;
};
class GMStorage
class JSONKeyStore
`
- Aliases: GMStore, GMStorage
- Type: GMStorage
`javascript
import GMStore from 'gm-storage'
const store = new GMStore()
store.setAll([['foo', 'bar'], ['baz', 'quux']])
store.size // 2
`
Constructs a Map-compatible instance which associates keys with their
corresponding values in the userscript engine's storage. GMStorageMap
instances are compatible with , where K extends (and defaults to)V
string and extends (and defaults to) the type of JSON-serializable values.
#### Options
The GMStorage constructor can take the following options:
##### strict
- Type: booleantrue
- Default:
`javascript
// don't need GM_deleteValue or GM_listValues
const store = new GMStorage({ strict: false })
store.set('foo', 'bar')
store.get('foo') // "bar"
`
In order to use all GMStorage methods, the following GM_* functions must be
defined (i.e. granted):
- GM_deleteValueGM_getValue
- GM_listValues
- GM_setValue
-
If this option is true (as it is by default), the existence of these functions
is checked when the store is created. If any of the functions are missing, an
exception is thrown.
If the option is false, they are not checked, and access to GM_* functions
required by unused storage methods need not be granted.
- Alias: JSONKeyStorage
- Type: JSONKeyStore
`javascript
import { JSONKeyStore } from 'gm-storage'
const store = new JSONKeyStore()
store.set(['foo'], 'bar')
store.set({ foo: 'bar' }, ['baz', 'quux'])
store.get(['foo']) // "bar"
store.get({ foo: 'bar' }) // ["baz", "quux"]
Array.from(store.keys()) // [["foo"], { foo: "bar" }]
`
This class is an extension of the GMStorage class which supports the automatic
conversion of keys to/from JSON. Apart from the options listed below, its
behavior, methods and properties are the same as GMStorage.
#### Options
The JSONKeyStore constructor can take the following options, in addition to
those supported by GMStorage:
##### canonical
- Type: booleantrue
- Default:
`javascript
const store = new JSONKeyStore({ canonical: true })
store.set({ foo: 'bar', baz: 'quux' }, 1)
store.set({ baz: 'quux', foo: 'bar' }, 2)
store.size // 1
store.get({ foo: 'bar', baz: 'quux' }) // 2
store.get({ baz: 'quux', foo: 'bar' }) // 2
`
`javascript
const store = new JSONKeyStore({ canonical: false })
store.set({ foo: 'bar', baz: 'quux' }, 1)
store.set({ baz: 'quux', foo: 'bar' }, 2)
store.size // 2
store.get({ foo: 'bar', baz: 'quux' }) // 1
store.get({ baz: 'quux', foo: 'bar' }) // 2
`
When converting JSON values to strings, JSONKeyStore uses a canonical
representation which ensures that values which contain (nested) objects have
the same JSON representation regardless of their order of construction (by
sorting the keys). This produces the expected results, but may have a
performance impact (e.g. on my system, it's around 6x slower than vanilla
JSON.stringify). In cases where this normalization isn't needed — e.g. where
the keys are known to not contain objects (with multiple keys), or where the
order is stable, or significant — it can be disabled by setting this option to
false.
#### clear
- Type: clear(): voidGM_deleteValue
- Requires: , GM_listValues
`javascript
const store = new GMStorage().setAll([['foo', 'bar'], ['baz', 'quux']])
store.size // 2
store.clear()
store.size // 0
`
Remove all entries from the store.
#### delete
- Type: delete(key: K): booleanGM_deleteValue
- Requires: , GM_getValue
`javascript
const store = new GMStorage().setAll([['foo', 'bar'], ['baz', 'quux']])
store.size // 2
store.delete('nope') // false
store.delete('foo') // true
store.has('foo') // false
store.size // 1
`
Delete the value with the specified key from the store. Returns true if the
value existed, false otherwise.
#### entries
- Type: entries(): Generator<[K, V]>GM_getValue
- Requires: , GM_listValuesSymbol.iterator
- Alias:
`javascript`
for (const [key, value] of store.entries()) {
console.log([key, value])
}
Returns an iterable which yields each key/value pair from the store.
#### forEach
- Type:
- forEach(callback: CallbackforEach(callback: Callback
- GM_getValue
- Requires: , GM_listValues
`javascript`
store.forEach((value, key) => {
console.log([key, value])
})
Iterates over each key/value pair in the store, passing them to the callback,
along with the store itself, and binding the optional second argument to this
inside the callback.
#### get
- Type:
- getget(key: K): V | undefined
- GM_getValue
- Requires:
`javascript`
const maybeAge = store.get('age')
const age = store.get('age', 42)
Returns the value corresponding to the supplied key, or the default value
(which is undefined by default) if it doesn't exist.
#### has
- Type: has(key: K): booleanGM_getValue
- Requires:
`javascript`
if (!store.has(key)) {
console.log('not found')
}
Returns true if a value with the supplied key exists in the store, false
otherwise.
#### keys
- Type: keys(): GeneratorGM_listValues
- Requires:
`javascript`
for (const key of store.keys()) {
console.log(key)
}
Returns an iterable collection of the store's keys.
Note that, for compatibility with Map#keys, the return value is iterable but
is not an array.
#### set
- Type: set(key: K, value: V): thisGM_setValue
- Requires:
`javascript`
store.set('foo', 'bar')
.set('baz', 'quux')
Add a value to the store under the supplied key. Returns the store for
chaining.
#### setAll
- Type: setAll(values?: Iterable<[K, V]>): thisGM_setValue
- Requires:
`javascript`
store.setAll([['foo', 'bar'], ['baz', 'quux']])
store.has('foo') // true
store.get('baz') // "quux"
Add entries (key/value pairs) to the store. Returns the store for chaining.
#### values
- Type: values(): GeneratorGM_getValue
- Requires: , GM_listValues
`javascript`
for (const value of store.values()) {
console.log(value)
}
Returns an iterable collection of the store's values.
#### size
- Type: numberGM_listValues
- Requires:
`javascript`
console.log(store.size)
Returns the number of values in the store.
#### Symbol.iterator
An alias for entries:
`javascript`
for (const [key, value] of store) {
console.log([key, value])
}
The following NPM scripts are available:
- build - compile the library for testing and save to the target directory
- build:doc - generate the README's TOC (table of contents)
- build:release - compile the library for release and save to the target directory
- clean - remove the target directory and its contents
- rebuild - clean the target directory and recompile the library
- test - recompile the library and run the test suite
- test:run - run the test suite
- typecheck - sanity check the library's type definitions
- any userscript engine with support for the Greasemonkey 3 storage API
- any browser with ES6 support
- the GM_* functions are accessed viaglobalThis`,
which may need to be polyfilled in older browsers
- Keyv - simple key-value storage with support for multiple backends
- GM_deleteValue
- GM_getValue
- GM_listValues
- GM_setValue
- Map
4.1.1
Copyright © 2020-2025 by chocolateboy.
This is free software; you can redistribute it and/or modify it under the terms
of the MIT license.
[jsDelivr]: https://cdn.jsdelivr.net/npm/gm-storage@4.1.1/dist/index.umd.min.js
[unpkg]: https://unpkg.com/gm-storage@4.1.1/dist/index.umd.min.js