dom.ts 12 KB

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