dom.ts 15 KB

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