dom.ts 11 KB

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