General purpose DOM/GreaseMonkey library that allows you to register listeners for when CSS selectors exist, intercept events, create persistent & synchronous data stores, modify the DOM more easily and much more.
Contains builtin TypeScript declarations. Supports ESM and CJS imports via a bundler and global declaration via @require or <script>
The library works in any DOM environment with or without the GreaseMonkey API, but some features will be unavailable or require special setup.
You may want to check out my template for userscripts in TypeScript that you can use to get started quickly. It also includes this library by default.
If you like using this library, please consider supporting the development β€οΈ
View the documentation of previous major versions:
v9.4.4 β’ v8.4.0 β’ v7.3.0 β’ v6.3.0 β’ v5.0.1 β’ v4.2.1 β’ v3.0.0 β’ v2.0.1 β’ v1.2.0 β’ v0.5.3
Note
In version 10.0.0, many of the platform-agnostic features were moved to the CoreUtils library.
Everything is re-exported by UserUtils for backwards compatibility, but you may want to consider using CoreUtils directly if you don't need any of the DOM- or GreaseMonkey-specific features or want control over the installed version of CoreUtils.
- Installation
- License
- Preamble (info about the documentation)
- UserUtils Features
- DOM:
- π§
Dialog- class for creating custom modal dialogs with a promise-based API and a generic, default style - π§
SelectorObserver- class that manages listeners that are called when selectors are found in the DOM - π£
getUnsafeWindow()- get the unsafeWindow object or fall back to the regular window object - π£
isDomLoaded()- check if the DOM has finished loading and can be queried and modified - π£
onDomLoad()- run a function or pause async execution until the DOM has finished loading (or immediately if DOM is already loaded) - π£
addParent()- add a parent element around another element - π£
addGlobalStyle()- add a global style to the page - π£
preloadImages()- preload images into the browser cache for faster loading later on - π£
openInNewTab()- open a link in a new tab - π£
interceptEvent()- conditionally intercepts events registered byaddEventListener()on any given EventTarget object - π£
interceptWindowEvent()- conditionally intercepts events registered byaddEventListener()on the window object - π£
isScrollable()- check if an element has a horizontal or vertical scroll bar - π£
observeElementProp()- observe changes to an element's property that can't be observed with MutationObserver - π£
getSiblingsFrame()- returns a frame of an element's siblings, with a given alignment and size - π£
setInnerHtmlUnsafe()- set the innerHTML of an element using a Trusted Types policy without sanitizing or escaping it - π£
probeElementStyle()- probe the computed style of a temporary element (get default font size, resolve CSS variables, etc.)
- π§
- Misc:
- π§
GMStorageEngine- storage engine class forDataStores using the GreaseMonkey API - π§
Mixins- class for creating mixin functions that allow multiple sources to modify a target value in a highly flexible way
- π§
- Translation:
- π£
tr.for()- translates a key for the specified language - π£
tr.use()- creates a translation function for the specified language - π£
tr.hasKey()- checks if a key exists in the given language - π£
tr.addTranslations()- add a flat or recursive translation object for a language - π£
tr.getTranslations()- returns the translation object for a language - π£
tr.deleteTranslations()- delete the translation object for a language - π£
tr.setFallbackLanguage()- set the fallback language used when a key is not found in the given language - π£
tr.getFallbackLanguage()- returns the fallback language - π£
tr.addTransform()- adds a transform function to the translation system for custom argument insertion and much more - π£
tr.deleteTransform()- removes a transform function - π©
tr.transforms- predefined transform functions for quickly adding custom argument insertion - π·
TrKeys- generic type that extracts all keys from a flat or recursive translation object into a union
- π£
- Errors
- π§
PlatformError- thrown when the current platform doesn't support a certain feature, like calling a DOM function in a non-DOM environment
- π§
- DOM:
- CoreUtils Features (re-exported for backwards compatibility)
- Array:
- π£
function randomItem()- Returns a random item from the given array - π£
function randomItemIndex()- Returns a random array item and index as a tuple - π£
function randomizeArray()- Returns a new array with the items in random order - π£
function takeRandomItem()- Returns a random array item and mutates the array to remove it - π£
function takeRandomItemIndex()- Returns a random array item and index as a tuple and mutates the array to remove it - π·
type NonEmptyArray- Non-empty array type
- π£
- Colors:
- π£
function darkenColor()- Darkens the given color by the given percentage - π£
function hexToRgb()- Converts a hex color string to an RGB object - π£
function lightenColor()- Lightens the given color by the given percentage - π£
function rgbToHex()- Converts an RGB object to a hex color string
- π£
- Crypto:
- π£
function abtoa()- Converts an ArrayBuffer to a string - π£
function atoab()- Converts a string to an ArrayBuffer - π£
function compress()- Compresses the given string using the given algorithm and encoding - π£
function decompress()- Decompresses the given string using the given algorithm and encoding - π£
function computeHash()- Computes a string's hash using the given algorithm - π£
function randomId()- Generates a random ID of the given length
- π£
- DataStore: - Cross-platform, general-purpose, sync/async hybrid, JSON-serializable database infrastructure:
- π§
class DataStore- The main class for the data store- π·
type DataStoreOptions- Options for the data store - π·
type DataMigrationsDict- Dictionary of data migration functions
- π·
- π§
class DataStoreSerializer- Serializes and deserializes data for multiple DataStore instances- π·
type DataStoreSerializerOptions- Options for the DataStoreSerializer - π·
type LoadStoresDataResult- Result of callingloadStoresData() - π·
type SerializedDataStore- Meta object and serialized data of a DataStore instance - π·
type StoreFilter- Filter for selecting data stores
- π·
- π§
class DataStoreEngine- Base class for DataStore storage engines, which handle the data storage- π·
type DataStoreEngineDSOptions- Reduced version ofDataStoreOptions
- π·
- Storage Engines:
- π§
class BrowserStorageEngine- Storage engine for browser environments (localStorage, sessionStorage)- π·
type BrowserStorageEngineOptions- Options for the browser storage engine
- π·
- π§
class FileStorageEngine- File-based storage engine for Node.js and Deno- π·
type FileStorageEngineOptions- Options for the file storage engine
- π·
- π§
- π§
- Debouncer:
- π£
function debounce()- Function wrapper for theDebouncerclass - π§
class Debouncer- Class that manages listeners whose calls are rate-limited- π·
type DebouncerType- The triggering type for the debouncer - π·
type DebouncedFunction- Function type that is returned by thedebounce()function - π·
type DebouncerEventMap- Event map type for theDebouncerclass
- π·
- π£
- Errors:
- π§
class DatedError- Base error class with adateproperty- π§
class ChecksumMismatchError- Error thrown when two checksums don't match - π§
class CustomError- Custom error with a configurable name for one-off situations - π§
class MigrationError- Error thrown in a failed data migration - π§
class ValidationError- Error while validating data
- π§
- π§
- Math:
- π£
function bitSetHas()- Checks if a bit is set in a bitset - π£
function clamp()- Clamps a number between a given range - π£
function digitCount()- Returns the number of digits in a number - π£
function formatNumber()- Formats a number to a string using the given locale and format identifier- π·
type NumberFormat- Number format identifier
- π·
- π£
function mapRange()- Maps a number from one range to another - π£
function overflowVal()- Makes sure a number is in a range by over- & underflowing it - π£
function randRange()- Returns a random number in the given range - π£
function roundFixed()- Rounds the given number to the given number of decimal places - π£
function valsWithin()- Checks if the given numbers are within a certain range of each other
- π£
- Misc:
- π£
function consumeGen()- Consumes aValueGenobject- π·
type ValueGen- A value that can be either type T, or a sync or async function that returns T
- π·
- π£
function consumeStringGen()- Consumes aStringGenobject- π·
type StringGen- A value that can be either of type string, or a sync or async function that returns a string
- π·
- π£
function fetchAdvanced()- Wrapper aroundfetch()with options like a timeout- π·
type FetchAdvancedOpts- Options for thefetchAdvanced()function
- π·
- π£
function getListLength()- Returns the length of aListLikeobject - π£
function pauseFor()- Pauses async execution for the given amount of time - π£
function pureObj()- Applies an object's props to a null object (object without prototype chain) or just returns a new null object - π£
function setImmediateInterval()- LikesetInterval(), but instantly calls the callback and supports passing anAbortSignal - π£
function setImmediateTimeoutLoop()- Like a recursivesetTimeout()loop, but instantly calls the callback and supports passing anAbortSignal - π£
function scheduleExit()- Schedules a process exit after the next event loop tick, to allow operations like IO writes to finish. - π£
function getCallStack()- Returns the current call stack, starting at the caller of this function.
- π£
- NanoEmitter:
- π§
class NanoEmitter- Simple, lightweight event emitter class that can be used in both FP and OOP, inspired byEventEmitterfromnode:events, based onnanoevents- π·
type NanoEmitterOptions- Options for theNanoEmitterclass
- π·
- π§
- Text:
- π£
function autoPlural()- Turns the given term into its plural form, depending on the given number or list length - π£
function capitalize()- Capitalizes the first letter of the given string - π£
function createProgressBar()- Creates a progress bar string with the given percentage and length- π©
const defaultPbChars- Default characters for the progress bar - π·
type ProgressBarChars- Type for the progress bar characters object
- π©
- π£
function joinArrayReadable()- Joins the given array into a string, using the given separators and last separator - π£
function secsToTimeStr()- Turns the given number of seconds into a string in the format(hh:)mm:sswith intelligent zero-padding - π£
function truncStr()- Truncates the given string to the given length
- π£
- Misc. Types:
- π·
type LooseUnion- A union type that allows for autocomplete suggestions as well as substitutions of the same type - π·
type ListLike- Any value with a quantifiablelength,countorsizeproperty - π·
type Newable- Any class reference that can be instantiated withnew - π·
type NonEmptyArray- Non-empty array type - π·
type NonEmptyString- String type with at least one character - π·
type NumberFormat- Number format identifier - π·
type Prettify- Makes the structure of a type more readable by fully expanding it (recursively) - π·
type SerializableVal- Any value that can be serialized to JSON - π·
type StringGen- A value that can be either of type string, or a sync or async function that returns a string - π·
type ValueGen- A value that can be either the generic type T, or a sync or async function that returns T - π·
type Stringifiable- Any value that can be implicitly converted to a string
- π·
- Array:
Note
π£ = function
π§ = class
π· = type
π© = const
Shameless plug: I made a template for userscripts in TypeScript that you can use to get started quickly. It also includes this library by default.
-
If you are using a bundler (like webpack, rollup, vite, etc.), you can install this package in one of the following ways:
npm i @sv443-network/userutils pnpm i @sv443-network/userutils yarn add @sv443-network/userutils npx jsr install @sv443-network/userutils deno add jsr:@sv443-network/userutilsThen import it in your script as usual:
// on Node: import { addGlobalStyle } from "@sv443-network/userutils"; // on Deno: import { addGlobalStyle } from "jsr:@sv443-network/userutils"; // you can also import the entire library as an object (not recommended because of worse treeshaking support): import * as UserUtils from "@sv443-network/userutils";
-
If you are not using a bundler, want to reduce the size of your script, or declared the package as external in your bundler, you can include the latest release by adding one of these directives to the userscript header, depending on your preferred CDN:
Versioned (recommended):
// @require https://cdn.jsdelivr.net/npm/@sv443-network/userutils@INSERT_VERSION/dist/UserUtils.user.js // @require https://unpkg.com/@sv443-network/userutils@INSERT_VERSION/dist/UserUtils.user.jsNon-versioned (not recommended because it auto-updates):
// @require https://update.greasyfork.org/scripts/472956/UserUtils.js // @require https://openuserjs.org/src/libs/Sv443/UserUtils.js -
If you are using this library in a generic DOM environment without access to the GreaseMonkey API, either download the latest release from the releases page to include in your project or add one of the following tags to the <head>:
<script src="https://cdn.jsdelivr.net/npm/@sv443-network/userutils@INSERT_VERSION/dist/UserUtils.umd.js"></script> <script src="https://unpkg.com/@sv443-network/userutils@INSERT_VERSION/dist/UserUtils.umd.js"></script>
Note
In order for your script not to break on a major library update, use one the versioned URLs above after replacing INSERT_VERSION with the desired version (e.g. 10.0.4) or the versioned URL that's shown at the top of the GreasyFork page.
-
Then, access the functions on the global variable
UserUtils:UserUtils.addGlobalStyle("body { background-color: red; }"); // or using object destructuring: const { clamp } = UserUtils; console.log(clamp(1, 5, 10)); // 5
-
If you're using TypeScript and it complains about the missing global variable
UserUtils, install the library using the package manager of your choice and add the following inside any.tsfile that is included in the final build:declare const UserUtils: typeof import("@sv443-network/userutils"); declare global { interface Window { UserUtils: typeof UserUtils; } }
-
If you're using a linter like ESLint, it might complain about the global variable
UserUtilsnot being defined. To fix this, add the following to your ESLint configuration file:"globals": { "UserUtils": "readonly" }
This library is licensed under the MIT License.
See the license file for details.
Made with β€οΈ by Sv443
If you like this library, please consider supporting the development