GM.getValue
Description
This method retrieves a value that was set with GM.setValue. See GM.setValue for details on the storage of these values.
Syntax
function GM.getValue( name, default )
Compatibility: Greasemonkey 4.0+
Arguments
name
String
The property name to get. See GM.setValue for details.default
- Optional. The default value to be returned when none has previously been set.
Returns
A Promise, rejected in case of error and otherwise resolved with:
- When this
name
has been set String
,Integer
orBoolean
as previously set- When this
name
has not been set, anddefault
is provided - The value passed as
default
- When this
name
has not been set, anddefault
is not provided undefined
Examples
Retrieving the value associated with the name 'foo':
console.log(await GM.getValue("foo"));
Retrieving the value associated with the name 'timezoneOffset' with a default value defined:
//GM.getValue() returns the value -5 (integer) if no value // associated with the name timezoneOffset is found in storage console.log(await GM.getValue("timezoneOffset", -5));
For structured data:
Used JSON.stringify()
to place an object into storage and then JSON.parse()
to convert it back.
//Note that if the value associated with foo is an invalid // JSON string, JSON.parse will fail. // Also note the default value is in quotes (thus a string) rather than an object literal var storedObject = JSON.parse(await GM.getValue("foo", "{}")); if (!storedObject) { //JSON.parse() should never return any value that type-casts to false, assume there is an // error in the input string console.warn('Error! JSON.parse failed - The stored value for "foo" is likely to be corrupted.'); throw; }
Complete end-to-end set and get example:
// ==UserScript== // @name Greasemonkey set-and-get Example // @description Stores and logs a counter of executions. // @grant GM.setValue // @grant GM.getValue // ==/UserScript== (async () => { let count_before = await GM.getValue('count', 0); // Note awaiting the set -- required so the next get sees this set. await GM.setValue('count', count_before + 1); // Get the value again, just to demonstrate order-of-operations. let count_after = await GM.getValue('count'); console.log('Greasemonkey set-and-get Example has run', count_after, 'times'); })();
Doing many gets/many sets can be slow.
Instead get/set one value (i.e. like with JSON.stringify()
above) or use Promise.all() to start all operations in parallel, then wait for all of them to complete.