Skip to content

A collection of utilities for implementing userscripts.

Notifications You must be signed in to change notification settings

CoeJoder/GM_wrench

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

34 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

GM_wrench

Greasemonkey Wrench.
A collection of helper functions and classes for userscripts. Includes a subset of the selenium-webdriver API.

Installation

Add the following to your userscript's metadata block:

// @require https://cdn.jsdelivr.net/gh/CoeJoder/GM_wrench@v1.5/dist/GM_wrench.min.js

If your userscript was already installed, you'll have to reinstall it to pickup the change. See documentation.

API Reference

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

A console logger which can change log-level via the GM menu.

new Logger([opts])

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");

GM_wrench.sleep(ms) ⇒ Promise.<void>

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);

GM_wrench.addCss(css)

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;
    }
`);

GM_wrench.addStylesheet(href)

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');

GM_wrench.isCssSelectorSupported(selector) ⇒ boolean

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");
}

GM_wrench.waitForKeyElements(selectorOrFunction, callback, [waitOnce], [interval], [maxIntervals])

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);

GM_wrench.By

Describes a mechanism for locating an element on the page.

Category: selenium-webdriver
See: webdriver.By

new By(using, value)

Param Type Description
using string The name of the location strategy to use.
value string The value to search for.

By.css(selector) ⇒ By

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.

By.id(id) ⇒ By

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.

By.className(name) ⇒ By

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.

By.linkText(text) ⇒ By

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.

GM_wrench.Condition

Defines a condition for use with wait.

Category: selenium-webdriver
See: webdriver.Condition

new Condition(message, fn)

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.

condition.description() ⇒ string

Returns: string - A description of this condition.

GM_wrench.ElementCondition ⇐ Condition

Defines a condition that will result in an Element.

Extends: Condition
Category: selenium-webdriver
See: webdriver.WebElementCondition

new ElementCondition(message, fn)

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.

GM_wrench.ElementPromise ⇐ Element

A promise that will be fulfilled with an Element.

Extends: Element
Implements: Promise<Element>
Category: selenium-webdriver
See: webdriver.WebElementPromise

new ElementPromise(el)

Param Type Description
el Promise.<!Element> A promise that will resolve to the promised element.

GM_wrench.TimeoutError ⇐ Error

An operation did not complete before its timeout expired.

Extends: Error
Category: selenium-webdriver
See: webdriver.TimeoutError

new TimeoutError([opt_error])

Param Type Description
[opt_error] string The error message, if any.

GM_wrench.until : object

Defines common conditions for use with wait.

Category: selenium-webdriver

until.elementLocated(locator) ⇒ ElementCondition

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.

until.elementsLocated(locator) ⇒ Condition.<!ParentNode, !(Promise.<?ArrayLike.<Element>>)>

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.

GM_wrench.wait([obj]) ⇒ Promise.<V> | ElementPromise

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 provided condition 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);

About

A collection of utilities for implementing userscripts.

Resources

Stars

Watchers

Forks

Packages

No packages published