Skip to content

Instantly share code, notes, and snippets.

@estelsmith
Last active November 23, 2024 23:11
Show Gist options
  • Save estelsmith/00dd7a0d58ccaaf39583b4b77723ad79 to your computer and use it in GitHub Desktop.
Save estelsmith/00dd7a0d58ccaaf39583b4b77723ad79 to your computer and use it in GitHub Desktop.
Functions to search and click elements by their text content.
/**
* This thing feels like a cheap jQuery knockoff. Cash would be better, but it doesn't have the extensible query engine, instead
* relying on document.querySelector().
* @see https://github.com/fabiospampinato/cash
*/
class Chainable {
#element;
constructor(element) {
this.#element = element;
}
get() {
return this.#element;
}
getFirst() {
return this.#element[0];
}
findHavingText(searchFor, options) {
return new Chainable(findHavingText(this.#element, searchFor, options));
}
findAncestorOfType(type, options) {
return new Chainable(findAncestorOfType(this.#element, type, options));
}
findClickable(searchFor) {
return this.findHavingText(searchFor).findAncestorOfType('a');
}
clickLink(searchFor) {
this.findClickable(searchFor).getFirst()?.click();
}
}
/**
* Find the element containing the given text.
*/
const findHavingText = (element, searchFor, { caseSensitive = false, returnFirst = false } = {}) => {
const stack = Array.from(element);
const found = [];
// Switch string comparison strategy based on whether it's a case-sensitive search.
const stringEquals = caseSensitive
? (needle, haystack) => haystack?.includes(needle)
: (needle, haystack) => haystack?.toLowerCase()?.includes(needle?.toLowerCase());
while (stack.length > 0) {
const current = stack.shift();
// Skip empty values.
if (!current) continue;
// Skip elements that are not visible.
if (!current.offsetParent) continue;
if (stringEquals(searchFor, current.textContent)) {
if (current?.children?.length === 0) {
if (returnFirst) {
return current;
}
found.push(current);
}
stack.push(...(current.children ?? []));
}
}
return found;
};
/**
* Find direct ancestors of an element that's of a given element type.
*/
const findAncestorOfType = (element, type, { returnFirst = false } = {}) => {
const stack = Array.from(element);
const found = [];
while (stack.length > 0) {
const current = stack.shift();
if (current.nodeName.toLowerCase() === type.toLowerCase()) {
if (returnFirst) {
return current;
}
found.push(current);
}
if (current.parentElement) {
stack.push(current.parentElement);
}
}
return found;
};
@estelsmith
Copy link
Author

estelsmith commented Nov 23, 2024

So, if you can get access to sizzle.js (the CSS selector engine behind jQuery) you could simplify the whole thing using just a CSS query. Sizzle is missing the :visible pseudo-selector, but that can be remedied by extending Sizzle with a visibility check based on offsetParent.

window.Sizzle.selectors.pseudos.visible = (e) => !!e.offsetParent;

Then it's a simple matter to find a Sign in link that's clickable. Sizzle('a:contains("Sign in"):visible')

Injecting Sizzle into the page is fairly straightforward. Simply inject the requisite <script> tag and wait for window.Sizzle to appear.

((callback) => {
    // Call the callback if lib's already loaded.
    if (window.Sizzle) {
        callback?.(window.Sizzle);
        return;
    }

    const element = document.createElement('script');
    element.setAttribute('src', 'https://cdnjs.cloudflare.com/ajax/libs/sizzle/2.3.10/sizzle.min.js');
    element.setAttribute('integrity', 'sha512-Zbkdi6xYzUdmR3FKlg3rnMCQMtODIEiipMONE0Nfcwnxid1jCzy1tJh1babTfmObSOjEIC/wkU1k8GyM/r6LLQ==');
    element.setAttribute('crossorigin', 'anonymous');
    element.setAttribute('referrerpolicy', 'no-referrer');
    document.body.append(element);

    const interval = setInterval(() => {
        const $ = window.Sizzle;
        if (!!$) {
            clearInterval(interval);

            // Add ":visible" pseudo-selector.
            $.selectors.pseudos.visible = (e) => !!e.offsetParent;

            callback?.($);
        }
    }, 100);
})(($) => {
    console.log($('a:contains("Sign in"):visible:first'));
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment