您需要先安装一个扩展,例如 篡改猴、Greasemonkey 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 Userscripts ,之后才能安装此脚本。
您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。
您需要先安装用户脚本管理器扩展后才能安装此脚本。
General purpose DOM/GreaseMonkey library: register listeners for when CSS selectors exist, intercept events, create persistent & synchronous data stores, modify the DOM more easily and much more
当前为
此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/472956/1234452/UserUtils.js
Library with various utilities for userscripts - register listeners for when CSS selectors exist, intercept events, 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 ❤️
onSelector()
addEventListener()
on any given EventTarget objectaddEventListener()
on the window object
npm i @sv443-network/userutils
Then, import it in your script as usual:
ts
import { addGlobalStyle } from "@sv443-network/userutils";
// or
import * as userUtils from "@sv443-network/userutils";
Shameless plug: I also have a webpack-based template for userscripts in TypeScript that you can use to get started quickly.
// @require https://gf.qytechs.cn/scripts/TODO
This library is written in TypeScript and contains builtin TypeScript declarations.
The usages and examples in this readme are written in TypeScript, but the library can also be used in plain JavaScript.
Some functions 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.
If the usage contains multiple definitions of the function, each line represents an overload and you can choose which one you want to use.
This library is licensed under the MIT License.
See the license file for details.
Usage:
onSelector<TElement = HTMLElement>(selector: string, options: {
listener: (elements: TElement | NodeListOf<TElement>) => void,
all?: boolean,
continuous?: boolean,
}): void
Registers a listener to be called whenever the element(s) behind a selector is/are found in the DOM.
If the selector already exists, the listener will be called immediately.
If all
is set to true
, querySelectorAll() will be used instead and the listener will return a NodeList of matching elements.
This will also include elements that were already found in a previous listener call.
If set to false
(default), querySelector() will be used and only the first matching element will be returned.
If continuous
is set to true
, the listener will not be deregistered after it was called once (defaults to false).
When using TypeScript, the generic TElement
can be used to specify the type of the element(s) that the listener will return.
⚠️ In order to use this function, initOnSelector()
has to be called as soon as possible.
This initialization function has to be called after DOMContentLoaded
is fired (or immediately if @run-at document-end
is set).
Calling onSelector() before DOMContentLoaded
is fired will not throw an error, but it also won't trigger listeners until the DOM is accessible.
Usage:
initOnSelector(options?: MutationObserverInit): void
Initializes the MutationObserver that is used by onSelector()
to check for the registered selectors whenever a DOM change occurs on the <body>
By default, this only checks if elements are added or removed (at any depth).
⚠️ This function needs to be run after the DOM has loaded (when using @run-at document-end
or after DOMContentLoaded
has fired).
The options object is passed directly to the MutationObserver.observe() method.
Note that options.subtree
and options.childList
will be set to true by default.
You may see all options here, but these are the important ones:
Set
options.attributes
totrue
to also check for attribute changes on every single descendant of the<body>
(defaults to false).
Setoptions.characterData
totrue
to also check for character data changes on every single descendant of the<body>
(defaults to false).⚠️ Using these extra options can have a performance impact on larger sites or sites with a constantly changing DOM.
Usage: getSelectorMap(): Map<string, OnSelectorOptions[]>
Returns a Map of all currently registered selectors and their options, including listener function.
Since multiple listeners can be registered for the same selector, the value of the Map is an array of OnSelectorOptions
objects.
Usage: 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.
Usage: insertAfter(beforeElement: HTMLElement, afterElement: HTMLElement): HTMLElement
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).
Usage: addParent(element: HTMLElement, newParent: HTMLElement): HTMLElement
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).
Usage: addGlobalStyle(css: string): void
Adds a global style to the page in form of a <style>
element that's inserted into the <head>
.
⚠️ This function needs to be run after the DOM has loaded (when using @run-at document-end
or after DOMContentLoaded
has fired).
Usage: preloadImages(urls: string[], rejects?: boolean): Promise<void>
Preloads images into browser cache by creating an invisible <img>
element for each URL passed.
The images will be loaded in parallel and the returned Promise will only resolve once all images have been loaded.
The resulting PromiseSettledResult array will contain the image elements if resolved, or an ErrorEvent if rejected, but only if rejects
is set to true.
Usage: openInNewTab(url: string): void
Creates an invisible anchor with a _blank
target and clicks it.
Contrary to window.open()
, this has a lesser chance to get blocked by the browser's popup blocker and doesn't open the URL as a new window.
This function has to be run in response to a user interaction event, else the browser might reject it.
⚠️ This function needs to be run after the DOM has loaded (when using @run-at document-end
or after DOMContentLoaded
has fired).
Usage: interceptEvent(eventObject: EventTarget, eventName: string, predicate: () => boolean): void
Intercepts all events dispatched on the eventObject
and prevents the listeners from being called as long as the predicate function returns a truthy value.
Calling this function will set the Error.stackTraceLimit
to 1000 (if it's not already higher) to ensure the stack trace is preserved.
⚠️ This function should be called as soon as possible (I recommend using @run-at document-start
), as it will only intercept events that are attached after this function is called.
Usage: interceptWindowEvent(eventName: string, predicate: () => boolean): void
Intercepts all events dispatched on the window
object and prevents the listeners from being called as long as the predicate function returns a truthy value.
This is essentially the same as interceptEvent()
, but automatically uses the unsafeWindow
(or falls back to regular window
).
⚠️ This function should be called as soon as possible (I recommend using @run-at document-start
), as it will only intercept events that are attached after this function is called.
Usage: amplifyMedia(mediaElement: HTMLMediaElement, multiplier?: number): AmplifyMediaResult
Amplifies the gain of a media element (like <audio>
or <video>
) by a given multiplier (defaults to 1.0).
This is how you can increase the volume of a media element beyond the default maximum volume of 1.0 or 100%.
Make sure to limit the multiplier to a reasonable value (clamp() is good for this), as it may cause clipping or bleeding eardrums.
⚠️ This function has to be run in response to a user interaction event, else the browser will reject it because of the strict autoplay policy.
Returns an object with the following properties:
| Property | Description |
| :-- | :-- |
| mediaElement
| The passed media element |
| amplify()
| A function to change the amplification level |
| getAmpLevel()
| A function to return the current amplification level |
| context
| The AudioContext instance |
| source
| The MediaElementSourceNode instance |
| gain
| The GainNode instance |
Usage: mapRange(value: number, range_1_min: number, range_1_max: number, range_2_min: number, range_2_max: number): number
Maps a number from one range to the spot it would be in another range.
Usages:
randRange(min: number, max: number): number
randRange(max: number): number
Returns a random number between min
and max
(inclusive).
If only one argument is passed, it will be used as the max
value and min
will be set to 0.
Usage: autoPlural(str: string, num: number | Array | NodeList): string
Automatically pluralizes a string if the given number is not 1.
If an array or NodeList is passed, the length of it will be used.
Usage: pauseFor(ms: number): Promise<void>
Pauses async execution for a given amount of time.
Usage: debounce(func: Function, timeout?: number): Function
Debounces a function, meaning that it will only be called once after a given amount of time.
This is very useful for functions that are called repeatedly, like event listeners, to remove extraneous calls.
The timeout will default to 300ms if left undefined.
Usage:
fetchAdvanced(url: string, options?: {
timeout?: number,
// any other options from fetch() except for signal
}): Promise<Response>
A wrapper around the native fetch()
function that adds options like a timeout property.
The timeout will default to 10 seconds if left undefined.
Usage: randomItem(array: Array): any
Returns a random item from an array.
Returns undefined if the array is empty.
Usage: randomItemIndex(array: Array): [item: any, index: number]
Returns a tuple of a random item and its index from an array.
If the array is empty, it will return undefined for both values.
Usage: takeRandomItem(array: Array): any
Returns a random item from an array and mutates the array by removing the item.
Returns undefined if the array is empty.
Usage: randomizeArray(array: Array): Array
Returns a copy of the array with its items in a random order.
If the array is empty, the originally passed array will be returned.
Made with ❤️ by Sv443
If you like this library, please consider supporting development
QingJ © 2025
镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址