Greasemonkey Wrench.
A collection of helper functions and classes for userscripts. Includes a subset of the selenium-webdriver API.
Add the following to your userscript's metadata block:
// @require https://cdn.jsdelivr.net/gh/CoeJoder/[email protected]/dist/GM_wrench.min.js
If your userscript was already installed, you'll have to reinstall it to pickup the change. See documentation.
Example (Wait up to 10 seconds to be logged in, then wait up to 3 seconds for a button to appear, then click on it)
(async ({wait, until, By}) => {
function isLoggedIn(username) {
return -1 != document.body.innerHTML.search(`Welcome back, ${username}`);
}
await wait({
condition: isLoggedIn,
input: 'CoeJoder',
timeout: 10000,
message: 'Not logged in.'
});
await wait({
condition: until.elementLocated(By.css('button')),
input: document,
timeout: 3000
}).click();
})(GM_wrench);
- GM_wrench
- .Logger
- .sleep(ms) ⇒
Promise.<void>
- .addCss(css)
- .addStylesheet(href)
- .isCssSelectorSupported(selector) ⇒
boolean
- .waitForKeyElements(selectorOrFunction, callback, [waitOnce], [interval], [maxIntervals])
- selenium-webdriver
- .By
- new By(using, value)
- .css(selector) ⇒
By
- .id(id) ⇒
By
- .className(name) ⇒
By
- .linkText(text) ⇒
By
- .Condition
- new Condition(message, fn)
- .description() ⇒
string
- .ElementCondition ⇐
Condition
- .ElementPromise ⇐
Element
- .TimeoutError ⇐
Error
- .until :
object
- .elementLocated(locator) ⇒
ElementCondition
- .elementsLocated(locator) ⇒
Condition.<!ParentNode, !(Promise.<?ArrayLike.<Element>>)>
- .elementLocated(locator) ⇒
- .wait([obj]) ⇒
Promise.<V>
|ElementPromise
- .By
A console logger which can change log-level via the GM menu.
Param | Type | Default | Description |
---|---|---|---|
[opts] | Object |
An object. | |
[opts.level] | string |
"info" |
The log-level. Options: trace, debug, info, warn, error, fatal |
[opts.prefix] | string | null |
"(script name)" |
The log message prefix. |
[opts.registerMenu] | boolean |
true |
Whether or not to register a log-level changer in the GM menu. |
[opts.menuLabels] | Array.<string> |
["trace", "debug", "info"] |
The log-levels to show in the GM menu. |
[opts.formatter] | function |
The log message formatter. |
Example
const logger = new GM_wrench.Logger();
logger.info("userscript loaded");
Sleep for the given amount of time.
Returns: Promise.<void>
- A promise that will be resolved when the sleep has finished.
See: webdriver.sleep
Param | Type | Description |
---|---|---|
ms | number |
The amount of time, in milliseconds, to sleep. |
Example
await GM_wrench.sleep(2000);
Add a new <style>
with the given text to the <head>
.
Param | Type | Description |
---|---|---|
css | string |
The CSS rules to add. |
Example
GM_wrench.addCss(`
p {
height: 50px;
}
`);
Add a new stylesheet <link>
to the <head>
.
Param | Type | Description |
---|---|---|
href | string |
The URL of the stylesheet. |
Example
GM_wrench.addStylesheet('https://fonts.googleapis.com/css?family=Open+Sans');
Check whether or not a given CSS selector is supported by the current browser.
Returns: boolean
- Whether or not the selector is supported by the current browser.
Param | Type | Description |
---|---|---|
selector | string |
The CSS selector. |
Example
if (!GM_wrench.isCssSelectorSupported(':has(x)')) {
throw new Error("Browser does not support the ':has(x)' pseudo-selector");
}
Detect and handle AJAXed content. Can force each element to be processed one or more times.
Param | Type | Default | Description |
---|---|---|---|
selectorOrFunction | string | function |
The selector string or function. | |
callback | function |
The callback function; takes a single DOM element as parameter. If returns true, element will be processed again on subsequent iterations. | |
[waitOnce] | boolean |
true |
Whether to stop after the first elements are found. |
[interval] | number |
300 |
The time (ms) to wait between iterations. |
[maxIntervals] | number |
-1 |
The max number of intervals to run (negative number for unlimited). |
Example
GM_wrench.waitForKeyElements('div.comments', (element) => {
element.innerHTML = 'This text inserted by waitForKeyElements().';
});
GM_wrench.waitForKeyElements(() => {
const iframe = document.querySelector('iframe');
if (iframe) {
const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
return iframeDoc.querySelectorAll('div.comments');
}
return null;
}, callbackFunc);
Describes a mechanism for locating an element on the page.
Category: selenium-webdriver
See: webdriver.By
- .By
- new By(using, value)
- .css(selector) ⇒
By
- .id(id) ⇒
By
- .className(name) ⇒
By
- .linkText(text) ⇒
By
Param | Type | Description |
---|---|---|
using | string |
The name of the location strategy to use. |
value | string |
The value to search for. |
Locates elements using a CSS selector.
Returns: By
- The new locator.
Category: selenium-webdriver
See: webdriver.By.css
Param | Type | Description |
---|---|---|
selector | string |
The CSS selector to use. |
Locates elements by the ID attribute. This locator uses the CSS selector *[id="$ID"]
, not document.getElementById
.
Returns: By
- The new locator.
Category: selenium-webdriver
See: webdriver.By.id
Param | Type | Description |
---|---|---|
id | string |
The ID to search for. |
Locates elements that have a specific class name.
Returns: By
- The new locator.
Category: selenium-webdriver
See: webdriver.By.className
Param | Type | Description |
---|---|---|
name | string |
The class name to search for. |
Locates link elements whose visible text matches the given string.
Returns: By
- The new locator.
Category: selenium-webdriver
See: webdriver.By.linkText
Param | Type | Description |
---|---|---|
text | string |
The link text to search for. |
Defines a condition for use with wait.
Category: selenium-webdriver
See: webdriver.Condition
Param | Type | Description |
---|---|---|
message | string |
A descriptive error message. Should complete the sentence "Waiting [...]". |
fn | function |
The condition function to evaluate on each iteration of the wait loop. |
Returns: string
- A description of this condition.
Defines a condition that will result in an Element.
Extends: Condition
Category: selenium-webdriver
See: webdriver.WebElementCondition
Param | Type | Description |
---|---|---|
message | string |
A descriptive error message. Should complete the sentence "Waiting [...]". |
fn | function |
The condition function to evaluate on each iteration of the wait loop. |
A promise that will be fulfilled with an Element.
Extends: Element
Implements: Promise<Element>
Category: selenium-webdriver
See: webdriver.WebElementPromise
Param | Type | Description |
---|---|---|
el | Promise.<!Element> |
A promise that will resolve to the promised element. |
An operation did not complete before its timeout expired.
Extends: Error
Category: selenium-webdriver
See: webdriver.TimeoutError
Param | Type | Description |
---|---|---|
[opt_error] | string |
The error message, if any. |
Defines common conditions for use with wait.
Category: selenium-webdriver
- .until :
object
- .elementLocated(locator) ⇒
ElementCondition
- .elementsLocated(locator) ⇒
Condition.<!ParentNode, !(Promise.<?ArrayLike.<Element>>)>
- .elementLocated(locator) ⇒
Creates a condition that will loop until an element is found with the given locator.
Returns: ElementCondition
- The new condition.
Category: selenium-webdriver
See: webdriver.until.elementLocated
Param | Type | Description |
---|---|---|
locator | By | function |
The locator to use. |
Creates a condition that will loop until at least one element is found with the given locator.
Returns: Condition.<!ParentNode, !(Promise.<?ArrayLike.<Element>>)>
- The new condition.
Category: selenium-webdriver
See: webdriver.until.elementsLocated
Param | Type | Description |
---|---|---|
locator | By | function |
The locator to use. |
Waits for a condition to evaluate to a "truthy" value. The condition may be specified by a Condition, as a custom function, or as any promise-like thenable.
For a Condition or function, the wait will repeatedly evaluate the condition until it returns a truthy value. If any errors occur while evaluating the condition, they will be allowed to propagate. In the event a condition returns a Promise, the polling loop will wait for it to be resolved and use the resolved value for whether the condition has been satisfied. The resolution time for a promise is always factored into whether a wait has timed out.
If the provided condition is an ElementCondition, then the wait will return a ElementPromise that will resolve to the element that satisfied the condition.
Returns: Promise.<V>
| ElementPromise
- A promise that will be resolved with the first truthy value returned
by the condition function, or rejected if the condition times out. If the input input condition is an
instance of an ElementCondition, the returned value will be an ElementPromise.
Category: selenium-webdriver
Throws:
TypeError
if the providedcondition
is not a valid type.
See
Param | Type | Default | Description |
---|---|---|---|
[obj] | Object |
An object. | |
[obj.condition] | PromiseLike.<V> | Condition.<T, V> | function |
The condition to wait on, defined as a promise, Condition object, or a function to evaluate as a condition. | |
[obj.input] | T |
The input value to pass to the evaluated conditions. | |
[obj.timeout] | number |
0 |
The duration in milliseconds, how long to wait for the condition to be true. |
[obj.pollTimeout] | number |
200 |
The duration in milliseconds, how long to wait between polling the condition. |
[obj.message] | string | function |
An optional message to use if the wait times out. |
Example
(async ({wait, until, By}) => {
await wait({
condition: until.elementLocated(By.css('button')),
input: document
}).click();
})(GM_wrench);