All files / src/helpers dom.ts

92% Statements 23/25
100% Branches 3/3
50% Functions 1/2
92% Lines 23/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 571x                                 1x 1x 6x 6x 6x   6x 6x   6x 6x 6x 6x 6x 6x     6x   6x 4x 4x 2x 2x   1x                   1x 1x      
/**
 * Finds the first HTMLElement with the given text in the tree.
 * @category Helpers
 * @param root - The root HTMLElement to search in
 * @param searchText - The text or RegExp to search for
 * @returns The HTMLElement with the given text, or undefined if not found
 * @example Search for simple string
 * ```typescript
 * const element = findElementWithText(document.body, "Hello, world!");
 * // Returns the HTMLElement with the text "Hello, world!"
 * ```
 * @example Search Amazon product stock
 * ```typescript
 * const element = findElementWithText(document.body, "left in stock", "span");
 * // Returns: <span class="a-size-base a-color-price">Only 1 left in stock - order soon.</span>
 * ```
 * @source
 */
export function findElementWithText(
  root: HTMLElement,
  searchText: string,
  elementTag: string = '*',
): HTMLElement | undefined {
  // The "." at the start is crucial—it means "look inside the context node"
  const xpath = `.//${elementTag}[contains(text(), '${searchText}')]`;
 
  const result = document.evaluate(
    xpath,
    root, // This sets the starting point
    null,
    XPathResult.FIRST_ORDERED_NODE_TYPE,
    null,
  );
 
  const node = result.singleNodeValue;
 
  if (node instanceof HTMLElement) {
    return node;
  }
  return undefined;
}
 
/**
 * Reloads the current page. A named seam over `window.location.reload()` so tests can
 * stub it (jsdom can't navigate, and its `location` can't be redefined).
 * @category Helpers
 * @returns Nothing; the page reloads as a side effect.
 * @example
 * ```typescript
 * reloadPage(); // the extension page reloads
 * ```
 * @source
 */
export function reloadPage(): void {
  window.location.reload();
}