dom.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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. Is set to `false` by default.
  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.addEventListener("load", () => res(image));
  54. image.addEventListener("error", (evt) => rejects && rej(evt));
  55. image.src = src;
  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. if(typeof window.GM === "object")
  69. GM.openInTab(href, background);
  70. }
  71. catch {
  72. const openElem = document.createElement("a");
  73. Object.assign(openElem, {
  74. className: "userutils-open-in-new-tab",
  75. target: "_blank",
  76. rel: "noopener noreferrer",
  77. tabIndex: -1,
  78. ariaHidden: "true",
  79. href,
  80. ...additionalProps,
  81. });
  82. Object.assign(openElem.style, {
  83. display: "none",
  84. pointerEvents: "none",
  85. });
  86. document.body.appendChild(openElem);
  87. openElem.click();
  88. // schedule removal after the click event has been processed
  89. setTimeout(openElem.remove, 0);
  90. }
  91. }
  92. /**
  93. * Intercepts the specified event on the passed object and prevents it from being called if the called {@linkcode predicate} function returns a truthy value.
  94. * If no predicate is specified, all events will be discarded.
  95. * 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.
  96. * Calling this function will set `Error.stackTraceLimit = 100` (if not already higher) to ensure the stack trace is preserved.
  97. */
  98. export function interceptEvent<
  99. TEvtObj extends EventTarget,
  100. TPredicateEvt extends Event
  101. > (
  102. eventObject: TEvtObj,
  103. eventName: Parameters<TEvtObj["addEventListener"]>[0],
  104. predicate: (event: TPredicateEvt) => boolean = () => true,
  105. ): void {
  106. // @ts-ignore
  107. if(typeof window.GM === "object" && GM?.info?.scriptHandler && GM.info.scriptHandler === "FireMonkey" && (eventObject === window || eventObject === getUnsafeWindow()))
  108. throw new PlatformError("Intercepting window events is not supported on FireMonkey due to the isolated context the userscript runs in.");
  109. // default is 25 on FF so this should hopefully be more than enough
  110. // @ts-ignore
  111. Error.stackTraceLimit = Math.max(Error.stackTraceLimit, 100);
  112. if(isNaN(Error.stackTraceLimit))
  113. Error.stackTraceLimit = 100;
  114. (function(original: typeof eventObject.addEventListener) {
  115. // @ts-ignore
  116. eventObject.__proto__.addEventListener = function(...args: Parameters<typeof eventObject.addEventListener>) {
  117. const origListener = typeof args[1] === "function" ? args[1] : args[1]?.handleEvent ?? (() => void 0);
  118. args[1] = function(...a) {
  119. if(args[0] === eventName && predicate((Array.isArray(a) ? a[0] : a) as TPredicateEvt))
  120. return;
  121. else
  122. return origListener.apply(this, a);
  123. };
  124. original.apply(this, args);
  125. };
  126. // @ts-ignore
  127. })(eventObject.__proto__.addEventListener);
  128. }
  129. /**
  130. * Intercepts the specified event on the window object and prevents it from being called if the called {@linkcode predicate} function returns a truthy value.
  131. * If no predicate is specified, all events will be discarded.
  132. * 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.
  133. * Calling this function will set `Error.stackTraceLimit = 100` (if not already higher) to ensure the stack trace is preserved.
  134. */
  135. export function interceptWindowEvent<TEvtKey extends keyof WindowEventMap>(
  136. eventName: TEvtKey,
  137. predicate: (event: WindowEventMap[TEvtKey]) => boolean = () => true,
  138. ): void {
  139. return interceptEvent(getUnsafeWindow(), eventName, predicate);
  140. }
  141. /** Checks if an element is scrollable in the horizontal and vertical directions */
  142. export function isScrollable(element: Element): Record<"vertical" | "horizontal", boolean> {
  143. const { overflowX, overflowY } = getComputedStyle(element);
  144. return {
  145. vertical: (overflowY === "scroll" || overflowY === "auto") && element.scrollHeight > element.clientHeight,
  146. horizontal: (overflowX === "scroll" || overflowX === "auto") && element.scrollWidth > element.clientWidth,
  147. };
  148. }
  149. /**
  150. * Executes the callback when the passed element's property changes.
  151. * Contrary to an element's attributes, properties can usually not be observed with a MutationObserver.
  152. * This function shims the getter and setter of the property to invoke the callback.
  153. *
  154. * [Source](https://stackoverflow.com/a/61975440)
  155. * @param property The name of the property to observe
  156. * @param callback Callback to execute when the value is changed
  157. */
  158. export function observeElementProp<
  159. TElem extends Element = HTMLElement,
  160. TPropKey extends keyof TElem = keyof TElem,
  161. > (
  162. element: TElem,
  163. property: TPropKey,
  164. callback: (oldVal: TElem[TPropKey], newVal: TElem[TPropKey]) => void
  165. ): void {
  166. const elementPrototype = Object.getPrototypeOf(element);
  167. // eslint-disable-next-line no-prototype-builtins
  168. if(elementPrototype.hasOwnProperty(property)) {
  169. const descriptor = Object.getOwnPropertyDescriptor(elementPrototype, property);
  170. Object.defineProperty(element, property, {
  171. get: function() {
  172. // @ts-ignore
  173. // eslint-disable-next-line prefer-rest-params
  174. return descriptor?.get?.apply(this, arguments);
  175. },
  176. set: function() {
  177. const oldValue = this[property];
  178. // @ts-ignore
  179. // eslint-disable-next-line prefer-rest-params
  180. descriptor?.set?.apply(this, arguments);
  181. const newValue = this[property];
  182. if(typeof callback === "function") {
  183. // @ts-ignore
  184. callback.bind(this, oldValue, newValue);
  185. }
  186. return newValue;
  187. }
  188. });
  189. }
  190. }
  191. /**
  192. * Returns a "frame" of the closest siblings of the {@linkcode refElement}, based on the passed amount of siblings and {@linkcode refElementAlignment}
  193. * @param refElement The reference element to return the relative closest siblings from
  194. * @param siblingAmount The amount of siblings to return
  195. * @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
  196. * @param includeRef If set to `true` (default), the provided {@linkcode refElement} will be included in the returned array at the corresponding position
  197. * @template TSibling The type of the sibling elements that are returned
  198. * @returns An array of sibling elements
  199. */
  200. export function getSiblingsFrame<
  201. TSibling extends Element = HTMLElement,
  202. > (
  203. refElement: Element,
  204. siblingAmount: number,
  205. refElementAlignment: "center-top" | "center-bottom" | "top" | "bottom" = "center-top",
  206. includeRef = true,
  207. ): TSibling[] {
  208. const siblings = [...refElement.parentNode?.childNodes ?? []] as TSibling[];
  209. const elemSiblIdx = siblings.indexOf(refElement as TSibling);
  210. if(elemSiblIdx === -1)
  211. throw new Error("Element doesn't have a parent node");
  212. if(refElementAlignment === "top")
  213. return [...siblings.slice(elemSiblIdx + Number(!includeRef), elemSiblIdx + siblingAmount + Number(!includeRef))];
  214. else if(refElementAlignment.startsWith("center-")) {
  215. // if the amount of siblings is even, one of the two center ones will be decided by the value of `refElementAlignment`
  216. const halfAmount = (refElementAlignment === "center-bottom" ? Math.ceil : Math.floor)(siblingAmount / 2);
  217. const startIdx = Math.max(0, elemSiblIdx - halfAmount);
  218. // if the amount of siblings is even, the top offset of 1 will be applied whenever `includeRef` is set to true
  219. const topOffset = Number(refElementAlignment === "center-top" && siblingAmount % 2 === 0 && includeRef);
  220. // if the amount of siblings is odd, the bottom offset of 1 will be applied whenever `includeRef` is set to true
  221. const btmOffset = Number(refElementAlignment === "center-bottom" && siblingAmount % 2 !== 0 && includeRef);
  222. const startIdxWithOffset = startIdx + topOffset + btmOffset;
  223. // filter out the reference element if `includeRef` is set to false,
  224. // then slice the array to the desired framing including the offsets
  225. return [
  226. ...siblings
  227. .filter((_, idx) => includeRef || idx !== elemSiblIdx)
  228. .slice(startIdxWithOffset, startIdxWithOffset + siblingAmount)
  229. ];
  230. }
  231. else if(refElementAlignment === "bottom")
  232. return [...siblings.slice(elemSiblIdx - siblingAmount + Number(includeRef), elemSiblIdx + Number(includeRef))];
  233. return [] as TSibling[];
  234. }
  235. let ttPolicy: { createHTML: (html: string) => string } | undefined;
  236. /**
  237. * Sets the innerHTML property of the provided element without any sanitation or validation.
  238. * 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.
  239. * 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.
  240. *
  241. * - ⚠️ This function does not perform any sanitization and should thus be used with utmost caution, as it can easily lead to XSS vulnerabilities!
  242. */
  243. export function setInnerHtmlUnsafe<TElement extends Element = HTMLElement>(element: TElement, html: string): TElement {
  244. // @ts-ignore
  245. if(!ttPolicy && typeof window?.trustedTypes?.createPolicy === "function") {
  246. // @ts-ignore
  247. ttPolicy = window.trustedTypes.createPolicy("_uu_set_innerhtml_unsafe", {
  248. createHTML: (unsafeHtml: string) => unsafeHtml,
  249. });
  250. }
  251. element.innerHTML = ttPolicy?.createHTML?.(html) ?? html;
  252. return element;
  253. }
  254. /**
  255. * Creates an invisible temporary element to probe its rendered style.
  256. * Has to be run after the `DOMContentLoaded` event has fired on the document object.
  257. * @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
  258. * @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
  259. * @param hideOffscreen Whether to hide the element offscreen, enabled by default - disable if you want to probe the position style properties of the element
  260. * @param parentElement The parent element to append the probe element to, defaults to `document.body`
  261. * @returns The value returned by the `probeElement` function
  262. */
  263. export function probeElementStyle<
  264. TValue,
  265. TElem extends HTMLElement = HTMLSpanElement,
  266. > (
  267. probeStyle: (style: CSSStyleDeclaration, element: TElem) => TValue,
  268. element?: TElem | (() => TElem),
  269. hideOffscreen = true,
  270. parentElement = document.body,
  271. ): TValue {
  272. const el = element
  273. ? typeof element === "function" ? element() : element
  274. : document.createElement("span") as TElem;
  275. if(hideOffscreen) {
  276. el.style.position = "absolute";
  277. el.style.left = "-9999px";
  278. el.style.top = "-9999px";
  279. el.style.zIndex = "-9999";
  280. }
  281. el.classList.add("_uu_probe_element");
  282. parentElement.appendChild(el);
  283. const style = window.getComputedStyle(el);
  284. const result = probeStyle(style, el);
  285. setTimeout(() => el.remove(), 1);
  286. return result;
  287. }
  288. /** Returns whether or not the DOM has finished loading */
  289. export function isDomLoaded(): boolean {
  290. return domReady;
  291. }
  292. /**
  293. * Executes a callback and/or resolves the returned Promise when the DOM has finished loading.
  294. * Immediately executes/resolves if the DOM is already loaded.
  295. * @param cb Callback to execute when the DOM has finished loading
  296. * @returns Returns a Promise that resolves when the DOM has finished loading
  297. */
  298. export function onDomLoad(cb?: () => void): Promise<void> {
  299. return new Promise((res) => {
  300. if(domReady) {
  301. cb?.();
  302. res();
  303. }
  304. else
  305. document.addEventListener("DOMContentLoaded", () => {
  306. cb?.();
  307. res();
  308. });
  309. });
  310. }