## UserUtils
Zero-dependency library with various utilities for userscripts - register listeners for when CSS selectors exist, intercept events, manage persistent user configurations, modify the DOM more easily and more.
Contains builtin TypeScript declarations. Webpack compatible and supports ESM and CJS.
If you like using this library, please consider [supporting the development ❤️](https://github.com/sponsors/Sv443)
## Table of Contents:
- [**Installation**](#installation)
- [**Preamble**](#preamble)
- [**License**](#license)
- [**Features**](#features)
- [**DOM:**](#dom)
- [SelectorObserver](#selectorobserver) - class that manages listeners that are called when selectors are found in the DOM
- [getUnsafeWindow()](#getunsafewindow) - get the unsafeWindow object or fall back to the regular window object
- [insertAfter()](#insertafter) - insert an element as a sibling after another element
- [addParent()](#addparent) - add a parent element around another element
- [addGlobalStyle()](#addglobalstyle) - add a global style to the page
- [preloadImages()](#preloadimages) - preload images into the browser cache for faster loading later on
- [openInNewTab()](#openinnewtab) - open a link in a new tab
- [interceptEvent()](#interceptevent) - conditionally intercepts events registered by `addEventListener()` on any given EventTarget object
- [interceptWindowEvent()](#interceptwindowevent) - conditionally intercepts events registered by `addEventListener()` on the window object
- [amplifyMedia()](#amplifymedia) - amplify an audio or video element's volume past the maximum of 100%
- [isScrollable()](#isscrollable) - check if an element has a horizontal or vertical scroll bar
- [**Math:**](#math)
- [clamp()](#clamp) - constrain a number between a min and max value
- [mapRange()](#maprange) - map a number from one range to the same spot in another range
- [randRange()](#randrange) - generate a random number between a min and max boundary
- [**Misc:**](#misc)
- [ConfigManager](#configmanager) - class that manages persistent userscript configurations, including data migration
- [autoPlural()](#autoplural) - automatically pluralize a string
- [pauseFor()](#pausefor) - pause the execution of a function for a given amount of time
- [debounce()](#debounce) - call a function only once, after a given amount of time
- [fetchAdvanced()](#fetchadvanced) - wrapper around the fetch API with a timeout option
- [insertValues()](#insertvalues) - insert values into a string at specified placeholders
- [**Arrays:**](#arrays)
- [randomItem()](#randomitem) - returns a random item from an array
- [randomItemIndex()](#randomitemindex) - returns a tuple of a random item and its index from an array
- [takeRandomItem()](#takerandomitem) - returns a random item from an array and mutates it to remove the item
- [randomizeArray()](#randomizearray) - returns a copy of the array with its items in a random order
- [**Translation:**](#translation)
- [tr()](#tr) - simple translation of a string to another language
- [tr.addLanguage()](#traddlanguage) - add a language and its translations
- [tr.setLanguage()](#trsetlanguage) - set the currently active language for translations
- [tr.getLanguage()](#trgetlanguage) - returns the currently active language
- [**Utility types for TypeScript:**](#utility-types)
- [Stringifiable](#stringifiable) - any value that is a string or can be converted to one (implicitly or explicitly)
## Installation:
- If you are using a bundler like webpack, you can install this package using npm:
```
npm i
@sv443-network/userutils
```
Then, import it in your script as usual:
```ts
import { addGlobalStyle } from "
@sv443-network/userutils";
// or just import everything (not recommended because this doesn't allow for treeshaking):
import * as UserUtils from "
@sv443-network/userutils";
```
Shameless plug: I made a [template for userscripts in TypeScript](https://github.com/Sv443/Userscript.ts) that you can use to get started quickly. It also includes this library by default.
- If you are not using a bundler, you can include the latest release from GreasyFork by adding this directive to the userscript header:
```
//
@require https://greasyfork.org/scripts/472956-userutils/code/UserUtils.js
```
Then, access the functions on the global variable `UserUtils`:
```ts
UserUtils.addGlobalStyle("body { background-color: red; }");
// or using object destructuring:
const { clamp } = UserUtils;
console.log(clamp(1, 5, 10); // 5
```
## Preamble:
This library is written in TypeScript and contains builtin TypeScript declarations.
Each feature has example code that can be expanded by clicking on the text "Example - click to view".
The usages and examples are written in TypeScript, but the library can also be used in plain JavaScript after removing the type annotations (and changing the imports if you are using CommonJS).
If the usage section contains multiple definitions of the function, each occurrence represents an overload and you can choose which one you want to use.
Some features require the `
@run-at` or `
@grant` directives to be tweaked in the userscript header or have other requirements.
Their documentation will contain a section marked by a warning emoji (⚠️) that will go into more detail.
## License:
This library is licensed under the MIT License.
See the [license file](./LICENSE.txt) for details.
## Features:
## DOM:
### SelectorObserver
Usage:
```ts
new SelectorObserver(baseElement: Element, options?: MutationObserverInit)
```
A class that manages listeners that are called when selectors are found in the DOM.
### Methods:
`addListener(selector: string, options: SelectorListenerOptions): void`
Adds a listener for the given selector.
`disable(): void`
`enable(): void`
`clearListeners(): void`
`removeAllListeners(selector: string): boolean`
`removeListener(selector: string, options: SelectorListenerOptions): boolean`
`getAllListeners(): Map`
`getListeners(selector: string): SelectorListenerOptions[] | undefined`
Example - click to view
```ts
import { SelectorObserver } from "@sv443-network/userutils";
```
### getUnsafeWindow()
Usage:
```ts
getUnsafeWindow(): Window
```
Returns the unsafeWindow object or falls back to the regular window object if the `
@grant unsafeWindow` is not given.
Userscripts are sandboxed and do not have access to the regular window object, so this function is useful for websites that reject some events that were dispatched by the userscript.
Example - click to view
```ts
import { getUnsafeWindow } from "@sv443-network/userutils";
// trick the site into thinking the mouse was moved:
const mouseEvent = new MouseEvent("mousemove", {
view: getUnsafeWindow(),
screenY: 69,
screenX: 420,
movementX: 10,
movementY: 0,
});
document.body.dispatchEvent(mouseEvent);
```
### insertAfter()
Usage:
```ts
insertAfter(beforeElement: Element, afterElement: Element): Element
```
Inserts the element passed as `afterElement` as a sibling after the passed `beforeElement`.
The passed `afterElement` will be returned.
⚠️ This function needs to be run after the DOM has loaded (when using `
@run-at document-end` or after `DOMContentLoaded` has fired).
Example - click to view
```ts
import { insertAfter } from "@sv443-network/userutils";
// insert a as a sibling next to an element
const beforeElement = document.querySelector("#before");
const afterElement = document.createElement("div");
afterElement.innerText = "After";
insertAfter(beforeElement, afterElement);
```
### addParent()
Usage:
```ts
addParent(element: Element, newParent: Element): Element
```
Adds a parent element around the passed `element` and returns the new parent.
Previously registered event listeners are kept intact.
⚠️ This function needs to be run after the DOM has loaded (when using `@run-at document-end` or after `DOMContentLoaded` has fired).
Example - click to view
```ts
import { addParent } from "@sv443-network/userutils";
// add an around an element
const element = document.querySelector("#element");
const newParent = document.createElement("a");
newParent.href = "https://example.org/";
addParent(element, newParent);
```
### addGlobalStyle()
Usage:
```ts
addGlobalStyle(css: string): void
```
Adds a global style to the page in form of a `