GM.getValue: Difference between revisions

From GreaseSpot Wiki
Jump to navigationJump to search
m Text replace - "top | back'' " to ""
Lil Devil (talk | contribs)
m replace _ with .
 
(25 intermediate revisions by 9 users not shown)
Line 1: Line 1:
{{DISPLAYTITLE: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: [[Version_history#4.0_2|Greasemonkey 4.0+]]
 
=== Arguments ===
 
; <code>name</code>
: <code>String</code> The property name to get. See [[GM.setValue#Arguments|GM.setValue]] for details.
; <code>default</code>
: Optional. The default value to be returned when none has previously been set.
 
=== Returns ===


== Description ==
A [[Promise]], rejected in case of error and otherwise resolved with:


This [[API_reference|API]] method retrieves a value that was set with [[GM_setValue]]. If nothing was set and a default value is passed, it returns that default. Failing that, it returns undefined.
; When this <code>name</code> has been set
: <code>String</code>, <code>Integer</code> or <code>Boolean</code> as previously set
; When this <code>name</code> has not been set, and <code>default</code> is provided
: The value passed as <code>default</code>
; When this <code>name</code> has not been set, and <code>default</code> is not provided
: <code>undefined</code>


Values are saved in the [http://developer.mozilla.org/en/docs/Code_snippets:Preferences Firefox preferences] back end and can be manually changed by typing [[mozillazine:About:config|about:config]] in the address bar and searching for the preference name "<code>greasemonkey.scriptvals.[[Metadata_block#.40namespace|namespace]]/[[Metadata_block#.40name|name]].foo</code>".
== Examples ==


[[#Examples|Examples]] | [[#See_Also|See Also]] | [[#Notes|Notes]]
Retrieving the value associated with the name 'foo':
<pre class='sample-good'>
console.log(await GM.getValue("foo"));
</pre>


== Syntax ==
Retrieving the value associated with the name 'timezoneOffset' with a default value defined:
<pre class='sample'>
//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));
</pre>


'''GM_getValue(''' ''name'', ''default'' ''')'''


:Value: Function
For structured data:
:Returns: String, Integer, Boolean, undefined and null<sup>[[Talk:GM_getValue|[1]]]</sup>
Used <code>JSON.stringify()</code> to place an object into storage and then <code>JSON.parse()</code> to convert it back.
:Compatibility: [[Version_history#0.3_beta|Greasemonkey 0.3b+]]


:{| cellpadding="5" style="border-style:solid; background:#FFFFE0;"
<pre class='sample'>
|+ Parameters
//Note that if the value associated with foo is an invalid
!style="background:#CC9900;"|'''Properties'''
//   JSON string, JSON.parse will fail.
|-
//   Also note the default value is in quotes (thus a string) rather than an object literal
| <code><span style="background:#FFFFE0;">[[#name |name]]</span></code>
|-
|<code><span style="background:#FFFFE0;">[[#default |default]]</span></code>
|}
:* All properties are optional except [[#name|name]].


=== Properties ===
var storedObject = JSON.parse(await GM.getValue("foo", "{}"));  
----
==== <code>name</code> ====
:Value: String
:Usage: <code>'''name''' = "PropertyName";</code>


:* Property name to retrieve.
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;
}
</pre>


Complete end-to-end set and get example:


==== <code>default</code> ====
<pre class='sample-good'>
:Value: String, Integer or Boolean
// ==UserScript==
:Usage: <code>'''default''' = 5;</code>
// @name        Greasemonkey set-and-get Example
// @description Stores and logs a counter of executions.
// @grant      GM.setValue
// @grant      GM.getValue
// ==/UserScript==


:* If [[GM_getValue#name|name]] is not found, then use this property to return a [[#default |default]] value. If [[#default |default]] is omitted JavaScript undefined is returned.
(async () => {
: Note: Using this property does not call [[GM_setValue]] and is by design.
  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);


[[#top|top]] | [[#Syntax|back]]
  // 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');
})();
</pre>


== Examples ==
Doing many gets/many sets can be slow.
{{Samp |1=<pre style="border: none; margin: inherit;">
Instead get/set one value (i.e. like with <code>JSON.stringify()</code> above) or use [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all Promise.all()] to start all operations in parallel, then wait for all of them to complete.
GM_log(GM_getValue("foo"));
</pre>}}


== See Also ==
== See Also ==
* [[GM_setValue]]
* [[GM_deleteValue]]
* [[GM_listValues]]


== Notes ==
* [[GM.setValue]]
* [[GM.deleteValue]]
* [[GM.listValues]]


[[Category:API_Reference|G]]
[[Category:API_Reference|G]]

Latest revision as of 00:24, 19 September 2018

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 or Boolean as previously set
When this name has not been set, and default is provided
The value passed as default
When this name has not been set, and default 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.

See Also