diff --git a/src/scriptlets/trusted-click-element.ts b/src/scriptlets/trusted-click-element.ts index e739ff077..92b21d05f 100644 --- a/src/scriptlets/trusted-click-element.ts +++ b/src/scriptlets/trusted-click-element.ts @@ -383,13 +383,50 @@ export function trustedClickElement( } }; - const observer = new MutationObserver(throttle(findElements, THROTTLE_DELAY_MS)); - observer.observe(document.documentElement, { - attributes: true, - childList: true, - subtree: true, - }); + /** + * Initializes a `MutationObserver` to watch for changes in the DOM. + * The observer is set up to monitor changes in attributes, child nodes, and subtree. + * A timeout is set to disconnect the observer if no elements are found within the specified time. + */ + const initializeMutationObserver = () => { + const observer = new MutationObserver(throttle(findElements, THROTTLE_DELAY_MS)); + observer.observe(document.documentElement, { + attributes: true, + childList: true, + subtree: true, + }); + + // Set timeout to disconnect observer if elements are not found within the specified time + setTimeout(() => observer.disconnect(), OBSERVER_TIMEOUT_MS); + }; + /** + * Checks if elements are already present in the DOM. + * If elements are found, the observer is disconnected and the elements are clicked. + * If elements are not found, the observer is initialized. + */ + const checkInitialElements = () => { + const foundElements = selectorsSequence.some((selector) => { + if (!selector) { + return false; + } + const element = queryShadowSelector(selector); + return !!element; + }); + if (foundElements) { + // Click previously collected elements and set canClick to true + findElements([], new MutationObserver(() => {})); + canClick = true; + } else { + // Initialize MutationObserver if elements were not found initially + initializeMutationObserver(); + } + }; + + // Run the initial check + checkInitialElements(); + + // If there's a delay before clicking elements, use a timeout if (parsedDelay) { setTimeout(() => { // Click previously collected elements @@ -397,8 +434,6 @@ export function trustedClickElement( canClick = true; }, parsedDelay); } - - setTimeout(() => observer.disconnect(), OBSERVER_TIMEOUT_MS); } trustedClickElement.names = [