dom.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. /**
  2. * @module lib/dom
  3. * This module contains various functions for working with the DOM - [see the documentation for more info](https://github.com/Sv443-Network/UserUtils/blob/main/docs.md#dom)
  4. */
  5. import { PlatformError } from "./errors.js";
  6. /** Whether the DOM has finished loading */
  7. let domReady = false;
  8. document.addEventListener("DOMContentLoaded", () => domReady = true);
  9. /**
  10. * Returns `unsafeWindow` if the `@grant unsafeWindow` is given, otherwise falls back to the regular `window`
  11. */
  12. export function getUnsafeWindow(): Window {
  13. try {
  14. // throws ReferenceError if the "@grant unsafeWindow" isn't present
  15. return unsafeWindow;
  16. }
  17. catch {
  18. return window;
  19. }
  20. }
  21. /**
  22. * Adds a parent container around the provided element
  23. * @returns Returns the new parent element
  24. */
  25. export function addParent<TElem extends Element, TParentElem extends Element>(element: TElem, newParent: TParentElem): TParentElem {
  26. const oldParent = element.parentNode;
  27. if(!oldParent)
  28. throw new Error("Element doesn't have a parent node");
  29. oldParent.replaceChild(newParent, element);
  30. newParent.appendChild(element);
  31. return newParent;
  32. }
  33. /**
  34. * Adds global CSS style in the form of a `<style>` element in the document's `<head>`
  35. * This needs to be run after the `DOMContentLoaded` event has fired on the document object (or instantly if `@run-at document-end` is used).
  36. * @param style CSS string
  37. * @returns Returns the created style element
  38. */
  39. export function addGlobalStyle(style: string): HTMLStyleElement {
  40. const styleElem = document.createElement("style");
  41. setInnerHtmlUnsafe(styleElem, style);
  42. document.head.appendChild(styleElem);
  43. return styleElem;
  44. }
  45. /**
  46. * Preloads an array of image URLs so they can be loaded instantly from the browser cache later on
  47. * @param rejects If set to `true`, the returned PromiseSettledResults will contain rejections for any of the images that failed to load
  48. * @returns Returns an array of `PromiseSettledResult` - each resolved result will contain the loaded image element, while each rejected result will contain an `ErrorEvent`
  49. */
  50. export function preloadImages(srcUrls: string[], rejects = false): Promise<PromiseSettledResult<HTMLImageElement>[]> {
  51. const promises = srcUrls.map(src => new Promise<HTMLImageElement>((res, rej) => {
  52. const image = new Image();
  53. image.src = src;
  54. image.addEventListener("load", () => res(image));
  55. image.addEventListener("error", (evt) => rejects && rej(evt));
  56. }));
  57. return Promise.allSettled(promises);
  58. }
  59. /**
  60. * Tries to use `GM.openInTab` to open the given URL in a new tab, otherwise if the grant is not given, creates an invisible anchor element and clicks it.
  61. * For the fallback to work, this function needs to be run in response to a user interaction event, else the browser might reject it.
  62. * @param href The URL to open in a new tab
  63. * @param background If set to `true`, the tab will be opened in the background - set to `undefined` (default) to use the browser's default behavior
  64. * @param additionalProps Additional properties to set on the anchor element (only applies when `GM.openInTab` is not available)
  65. */
  66. export function openInNewTab(href: string, background?: boolean, additionalProps?: Partial<HTMLAnchorElement>): void {
  67. try {
  68. GM.openInTab?.(href, background);
  69. }
  70. catch {
  71. const openElem = document.createElement("a");
  72. Object.assign(openElem, {
  73. className: "userutils-open-in-new-tab",
  74. target: "_blank",
  75. rel: "noopener noreferrer",
  76. tabIndex: -1,
  77. ariaHidden: "true",
  78. href,
  79. ...additionalProps,
  80. });
  81. Object.assign(openElem.style, {
  82. display: "none",
  83. pointerEvents: "none",
  84. });
  85. document.body.appendChild(openElem);
  86. openElem.click();
  87. // schedule removal after the click event has been processed
  88. setTimeout(openElem.remove, 0);
  89. }
  90. }
  91. /**
  92. * Intercepts the specified event on the passed object and prevents it from being called if the called {@linkcode predicate} function returns a truthy value.
  93. * If no predicate is specified, all events will be discarded.
  94. * This function should be called as soon as possible (I recommend using `@run-at document-start`), as it will only intercept events that are added after this function is called.
  95. * Calling this function will set `Error.stackTraceLimit = 100` (if not already higher) to ensure the stack trace is preserved.
  96. */
  97. export function interceptEvent<
  98. TEvtObj extends EventTarget,
  99. TPredicateEvt extends Event
  100. > (
  101. eventObject: TEvtObj,
  102. eventName: Parameters<TEvtObj["addEventListener"]>[0],
  103. predicate: (event: TPredicateEvt) => boolean = () => true,
  104. ): void {
  105. // @ts-ignore
  106. if(GM?.info?.scriptHandler && GM.info.scriptHandler === "FireMonkey" && (eventObject === window || eventObject === getUnsafeWindow()))
  107. throw new PlatformError("Intercepting window events is not supported on FireMonkey due to the isolated context the userscript runs in.");
  108. // default is 25 on FF so this should hopefully be more than enough
  109. // @ts-ignore
  110. Error.stackTraceLimit = Math.max(Error.stackTraceLimit, 100);
  111. if(isNaN(Error.stackTraceLimit))
  112. Error.stackTraceLimit = 100;
  113. (function(original: typeof eventObject.addEventListener) {
  114. // @ts-ignore
  115. eventObject.__proto__.addEventListener = function(...args: Parameters<typeof eventObject.addEventListener>) {
  116. const origListener = typeof args[1] === "function" ? args[1] : args[1]?.handleEvent ?? (() => void 0);
  117. args[1] = function(...a) {
  118. if(args[0] === eventName && predicate((Array.isArray(a) ? a[0] : a) as TPredicateEvt))
  119. return;
  120. else
  121. return origListener.apply(this, a);
  122. };
  123. original.apply(this, args);
  124. };
  125. // @ts-ignore
  126. })(eventObject.__proto__.addEventListener);
  127. }
  128. /**
  129. * Intercepts the specified event on the window object and prevents it from being called if the called {@linkcode predicate} function returns a truthy value.
  130. * If no predicate is specified, all events will be discarded.
  131. * This function should be called as soon as possible (I recommend using `@run-at document-start`), as it will only intercept events that are added after this function is called.
  132. * Calling this function will set `Error.stackTraceLimit = 100` (if not already higher) to ensure the stack trace is preserved.
  133. */
  134. export function interceptWindowEvent<TEvtKey extends keyof WindowEventMap>(
  135. eventName: TEvtKey,
  136. predicate: (event: WindowEventMap[TEvtKey]) => boolean = () => true,
  137. ): void {
  138. return interceptEvent(getUnsafeWindow(), eventName, predicate);
  139. }
  140. /** Checks if an element is scrollable in the horizontal and vertical directions */
  141. export function isScrollable(element: Element): Record<"vertical" | "horizontal", boolean> {
  142. const { overflowX, overflowY } = getComputedStyle(element);
  143. return {
  144. vertical: (overflowY === "scroll" || overflowY === "auto") && element.scrollHeight > element.clientHeight,
  145. horizontal: (overflowX === "scroll" || overflowX === "auto") && element.scrollWidth > element.clientWidth,
  146. };
  147. }
  148. /**
  149. * Executes the callback when the passed element's property changes.
  150. * Contrary to an element's attributes, properties can usually not be observed with a MutationObserver.
  151. * This function shims the getter and setter of the property to invoke the callback.
  152. *
  153. * [Source](https://stackoverflow.com/a/61975440)
  154. * @param property The name of the property to observe
  155. * @param callback Callback to execute when the value is changed
  156. */
  157. export function observeElementProp<
  158. TElem extends Element = HTMLElement,
  159. TPropKey extends keyof TElem = keyof TElem,
  160. > (
  161. element: TElem,
  162. property: TPropKey,
  163. callback: (oldVal: TElem[TPropKey], newVal: TElem[TPropKey]) => void
  164. ): void {
  165. const elementPrototype = Object.getPrototypeOf(element);
  166. // eslint-disable-next-line no-prototype-builtins
  167. if(elementPrototype.hasOwnProperty(property)) {
  168. const descriptor = Object.getOwnPropertyDescriptor(elementPrototype, property);
  169. Object.defineProperty(element, property, {
  170. get: function() {
  171. // @ts-ignore
  172. // eslint-disable-next-line prefer-rest-params
  173. return descriptor?.get?.apply(this, arguments);
  174. },
  175. set: function() {
  176. const oldValue = this[property];
  177. // @ts-ignore
  178. // eslint-disable-next-line prefer-rest-params
  179. descriptor?.set?.apply(this, arguments);
  180. const newValue = this[property];
  181. if(typeof callback === "function") {
  182. // @ts-ignore
  183. callback.bind(this, oldValue, newValue);
  184. }
  185. return newValue;
  186. }
  187. });
  188. }
  189. }
  190. /**
  191. * Returns a "frame" of the closest siblings of the {@linkcode refElement}, based on the passed amount of siblings and {@linkcode refElementAlignment}
  192. * @param refElement The reference element to return the relative closest siblings from
  193. * @param siblingAmount The amount of siblings to return
  194. * @param refElementAlignment Can be set to `center-top` (default), `center-bottom`, `top`, or `bottom`, which will determine where the relative location of the provided {@linkcode refElement} is in the returned array
  195. * @param includeRef If set to `true` (default), the provided {@linkcode refElement} will be included in the returned array at the corresponding position
  196. * @template TSibling The type of the sibling elements that are returned
  197. * @returns An array of sibling elements
  198. */
  199. export function getSiblingsFrame<
  200. TSibling extends Element = HTMLElement,
  201. > (
  202. refElement: Element,
  203. siblingAmount: number,
  204. refElementAlignment: "center-top" | "center-bottom" | "top" | "bottom" = "center-top",
  205. includeRef = true,
  206. ): TSibling[] {
  207. const siblings = [...refElement.parentNode?.childNodes ?? []] as TSibling[];
  208. const elemSiblIdx = siblings.indexOf(refElement as TSibling);
  209. if(elemSiblIdx === -1)
  210. throw new Error("Element doesn't have a parent node");
  211. if(refElementAlignment === "top")
  212. return [...siblings.slice(elemSiblIdx + Number(!includeRef), elemSiblIdx + siblingAmount + Number(!includeRef))];
  213. else if(refElementAlignment.startsWith("center-")) {
  214. // if the amount of siblings is even, one of the two center ones will be decided by the value of `refElementAlignment`
  215. const halfAmount = (refElementAlignment === "center-bottom" ? Math.ceil : Math.floor)(siblingAmount / 2);
  216. const startIdx = Math.max(0, elemSiblIdx - halfAmount);
  217. // if the amount of siblings is even, the top offset of 1 will be applied whenever `includeRef` is set to true
  218. const topOffset = Number(refElementAlignment === "center-top" && siblingAmount % 2 === 0 && includeRef);
  219. // if the amount of siblings is odd, the bottom offset of 1 will be applied whenever `includeRef` is set to true
  220. const btmOffset = Number(refElementAlignment === "center-bottom" && siblingAmount % 2 !== 0 && includeRef);
  221. const startIdxWithOffset = startIdx + topOffset + btmOffset;
  222. // filter out the reference element if `includeRef` is set to false,
  223. // then slice the array to the desired framing including the offsets
  224. return [
  225. ...siblings
  226. .filter((_, idx) => includeRef || idx !== elemSiblIdx)
  227. .slice(startIdxWithOffset, startIdxWithOffset + siblingAmount)
  228. ];
  229. }
  230. else if(refElementAlignment === "bottom")
  231. return [...siblings.slice(elemSiblIdx - siblingAmount + Number(includeRef), elemSiblIdx + Number(includeRef))];
  232. return [] as TSibling[];
  233. }
  234. let ttPolicy: { createHTML: (html: string) => string } | undefined;
  235. /**
  236. * Sets the innerHTML property of the provided element without any sanitation or validation.
  237. * Uses a [Trusted Types policy](https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API) on Chromium-based browsers to trick the browser into thinking the HTML is safe.
  238. * Use this if the page makes use of the CSP directive `require-trusted-types-for 'script'` and throws a "This document requires 'TrustedHTML' assignment" error on Chromium-based browsers.
  239. *
  240. * - ⚠️ This function does not perform any sanitization and should thus be used with utmost caution, as it can easily lead to XSS vulnerabilities!
  241. */
  242. export function setInnerHtmlUnsafe<TElement extends Element = HTMLElement>(element: TElement, html: string): TElement {
  243. // @ts-ignore
  244. if(!ttPolicy && typeof window?.trustedTypes?.createPolicy === "function") {
  245. // @ts-ignore
  246. ttPolicy = window.trustedTypes.createPolicy("_uu_set_innerhtml_unsafe", {
  247. createHTML: (unsafeHtml: string) => unsafeHtml,
  248. });
  249. }
  250. element.innerHTML = ttPolicy?.createHTML?.(html) ?? html;
  251. return element;
  252. }
  253. /**
  254. * Creates an invisible temporary element to probe its rendered style.
  255. * Has to be run after the `DOMContentLoaded` event has fired on the document object.
  256. * @param probeStyle Function to probe the element's style. First argument is the element's style object from [`window.getComputedStyle()`](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle), second argument is the element itself
  257. * @param element The element to probe, or a function that creates and returns the element - should not be added to the DOM prior to calling this function! - all probe elements will have the class `_uu_probe_element` added to them
  258. * @param hideOffscreen Whether to hide the element offscreen, enabled by default - disable if you want to probe the position style properties of the element
  259. * @param parentElement The parent element to append the probe element to, defaults to `document.body`
  260. * @returns The value returned by the `probeElement` function
  261. */
  262. export function probeElementStyle<
  263. TValue,
  264. TElem extends HTMLElement = HTMLSpanElement,
  265. > (
  266. probeStyle: (style: CSSStyleDeclaration, element: TElem) => TValue,
  267. element?: TElem | (() => TElem),
  268. hideOffscreen = true,
  269. parentElement = document.body,
  270. ): TValue {
  271. const el = element
  272. ? typeof element === "function" ? element() : element
  273. : document.createElement("span") as TElem;
  274. if(hideOffscreen) {
  275. el.style.position = "absolute";
  276. el.style.left = "-9999px";
  277. el.style.top = "-9999px";
  278. el.style.zIndex = "-9999";
  279. }
  280. el.classList.add("_uu_probe_element");
  281. parentElement.appendChild(el);
  282. const style = window.getComputedStyle(el);
  283. const result = probeStyle(style, el);
  284. setTimeout(() => el.remove(), 1);
  285. return result;
  286. }
  287. /** Returns whether or not the DOM has finished loading */
  288. export function isDomLoaded(): boolean {
  289. return domReady;
  290. }
  291. /**
  292. * Executes a callback and/or resolves the returned Promise when the DOM has finished loading.
  293. * Immediately executes/resolves if the DOM is already loaded.
  294. * @param cb Callback to execute when the DOM has finished loading
  295. * @returns Returns a Promise that resolves when the DOM has finished loading
  296. */
  297. export function onDomLoad(cb?: () => void): Promise<void> {
  298. return new Promise((res) => {
  299. if(domReady) {
  300. cb?.();
  301. res();
  302. }
  303. else
  304. document.addEventListener("DOMContentLoaded", () => {
  305. cb?.();
  306. res();
  307. });
  308. });
  309. }