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
npm install @sv443-network/userutils@require or 




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.
Dialog - class for creating custom modal dialogs with a promise-based API and a generic, default styleSelectorObserver - class that manages listeners that are called when selectors are found in the DOMgetUnsafeWindow() - get the unsafeWindow object or fall back to the regular window objectisDomLoaded() - check if the DOM has finished loading and can be queried and modifiedonDomLoad() - 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 elementaddGlobalStyle() - add a global style to the pagepreloadImages() - preload images into the browser cache for faster loading later onopenInNewTab() - open a link in a new tabinterceptEvent() - conditionally intercepts events registered by addEventListener() on any given EventTarget objectinterceptWindowEvent() - conditionally intercepts events registered by addEventListener() on the window objectisScrollable() - check if an element has a horizontal or vertical scroll barobserveElementProp() - observe changes to an element's property that can't be observed with MutationObservergetSiblingsFrame() - returns a frame of an element's siblings, with a given alignment and sizesetInnerHtmlUnsafe() - set the innerHTML of an element using a Trusted Types policy without sanitizing or escaping itprobeElementStyle() - probe the computed style of a temporary element (get default font size, resolve CSS variables, etc.)GMStorageEngine - storage engine class for DataStores using the GreaseMonkey APIMixins - class for creating mixin functions that allow multiple sources to modify a target value in a highly flexible waytr.for() - translates a key for the specified languagetr.use() - creates a translation function for the specified languagetr.hasKey() - checks if a key exists in the given languagetr.addTranslations() - add a flat or recursive translation object for a languagetr.getTranslations() - returns the translation object for a languagetr.deleteTranslations() - delete the translation object for a languagetr.setFallbackLanguage() - set the fallback language used when a key is not found in the given languagetr.getFallbackLanguage() - returns the fallback languagetr.addTransform() - adds a transform function to the translation system for custom argument insertion and much moretr.deleteTransform() - removes a transform functiontr.transforms - predefined transform functions for quickly adding custom argument insertionTrKeys - generic type that extracts all keys from a flat or recursive translation object into a unionPlatformError - thrown when the current platform doesn't support a certain feature, like calling a DOM function in a non-DOM environmentfunction randomItem() - Returns a random item from the given arrayfunction randomItemIndex() - Returns a random array item and index as a tuplefunction randomizeArray() - Returns a new array with the items in random orderfunction takeRandomItem() - Returns a random array item and mutates the array to remove itfunction takeRandomItemIndex() - Returns a random array item and index as a tuple and mutates the array to remove ittype NonEmptyArray - Non-empty array typefunction darkenColor() - Darkens the given color by the given percentagefunction hexToRgb() - Converts a hex color string to an RGB objectfunction lightenColor() - Lightens the given color by the given percentagefunction rgbToHex() - Converts an RGB object to a hex color stringfunction abtoa() - Converts an ArrayBuffer to a stringfunction atoab() - Converts a string to an ArrayBufferfunction compress() - Compresses the given string using the given algorithm and encodingfunction decompress() - Decompresses the given string using the given algorithm and encodingfunction computeHash() - Computes a string's hash using the given algorithmfunction randomId() - Generates a random ID of the given lengthclass DataStore - The main class for the data storetype DataStoreOptions - Options for the data storetype DataMigrationsDict - Dictionary of data migration functionstype DataStoreData - The type of the serializable dataclass DataStoreSerializer - Serializes and deserializes data for multiple DataStore instancestype DataStoreSerializerOptions - Options for the DataStoreSerializertype LoadStoresDataResult - Result of calling loadStoresData()type SerializedDataStore - Meta object and serialized data of a DataStore instancetype StoreFilter - Filter for selecting data storesclass DataStoreEngine - Base class for DataStore storage engines, which handle the data storagetype DataStoreEngineDSOptions - Reduced version of DataStoreOptionsclass BrowserStorageEngine - Storage engine for browser environments (localStorage, sessionStorage)type BrowserStorageEngineOptions - Options for the browser storage engineclass FileStorageEngine - File-based storage engine for Node.js and Denotype FileStorageEngineOptions - Options for the file storage enginefunction debounce() - Function wrapper for the Debouncer classclass Debouncer - Class that manages listeners whose calls are rate-limitedtype DebouncerType - The triggering type for the debouncertype DebouncedFunction - Function type that is returned by the debounce() functiontype DebouncerEventMap - Event map type for the Debouncer classclass DatedError - Base error class with a date propertyclass ChecksumMismatchError - Error thrown when two checksums don't matchclass CustomError - Custom error with a configurable name for one-off situationsclass MigrationError - Error thrown in a failed data migrationclass ValidationError - Error while validating datafunction bitSetHas() - Checks if a bit is set in a bitsetfunction clamp() - Clamps a number between a given rangefunction digitCount() - Returns the number of digits in a numberfunction formatNumber() - Formats a number to a string using the given locale and format identifiertype NumberFormat - Number format identifierfunction mapRange() - Maps a number from one range to anotherfunction overflowVal() - Makes sure a number is in a range by over- & underflowing itfunction randRange() - Returns a random number in the given rangefunction roundFixed() - Rounds the given number to the given number of decimal placesfunction valsWithin() - Checks if the given numbers are within a certain range of each otherfunction consumeGen() - Consumes a ValueGen objecttype ValueGen - A value that can be either type T, or a sync or async function that returns Tfunction consumeStringGen() - Consumes a StringGen objecttype StringGen - A value that can be either of type string, or a sync or async function that returns a stringfunction fetchAdvanced() - Wrapper around fetch() with options like a timeouttype FetchAdvancedOpts - Options for the fetchAdvanced() functionfunction getListLength() - Returns the length of a ListLike objectfunction pauseFor() - Pauses async execution for the given amount of timefunction pureObj() - Applies an object's props to a null object (object without prototype chain) or just returns a new null objectfunction setImmediateInterval() - Like setInterval(), but instantly calls the callback and supports passing an AbortSignalfunction setImmediateTimeoutLoop() - Like a recursive setTimeout() loop, but instantly calls the callback and supports passing an AbortSignalfunction 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.class NanoEmitter - Simple, lightweight event emitter class that can be used in both FP and OOP, inspired by EventEmitter from node:events, based on nanoeventstype NanoEmitterOptions - Options for the NanoEmitter classfunction autoPlural() - Turns the given term into its plural form, depending on the given number or list lengthfunction capitalize() - Capitalizes the first letter of the given stringfunction createProgressBar() - Creates a progress bar string with the given percentage and lengthconst defaultPbChars - Default characters for the progress bartype ProgressBarChars - Type for the progress bar characters objectfunction joinArrayReadable() - Joins the given array into a string, using the given separators and last separatorfunction secsToTimeStr() - Turns the given number of seconds into a string in the format (hh:)mm:ss with intelligent zero-paddingfunction truncStr() - Truncates the given string to the given lengthtype LooseUnion - A union type that allows for autocomplete suggestions as well as substitutions of the same typetype ListLike - Any value with a quantifiable length, count or size propertytype Newable - Any class reference that can be instantiated with newtype NonEmptyArray - Non-empty array typetype NonEmptyString - String type with at least one charactertype NumberFormat - Number format identifiertype Prettify - Makes the structure of a type more readable by fully expanding it (recursively)type SerializableVal - Any value that can be serialized to JSONtype StringGen - A value that can be either of type string, or a sync or async function that returns a stringtype ValueGen - A value that can be either the generic type T, or a sync or async function that returns Ttype Stringifiable - Any value that can be implicitly converted to a string> [!NOTE]
> 🟣 = function
> 🟧 = class
> 🔷 = type
> 🟩 = const
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/userutils
`
Then import it in your script as usual:
`ts
// 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/index.global.js
// @require https://unpkg.com/@sv443-network/userutils@INSERT_VERSION/dist/index.global.js
`
Non-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>:
`html
`> [!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. 8.3.2) or the versioned URL that's shown at the top of the GreasyFork page.
- 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
`
- 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 .ts file that is included in the final build:
`ts
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
UserUtils not being defined. To fix this, add the following to your ESLint configuration file:
`json
"globals": {
"UserUtils": "readonly"
}
``Made with ❤️ by Sv443
If you like this library, please consider supporting the development