dom.ts 15 KB

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