Skip to content

Instantly share code, notes, and snippets.

@patocl
Created November 30, 2024 11:26
Show Gist options
  • Save patocl/a573269b00a129c0f0155bdb06b69bcd to your computer and use it in GitHub Desktop.
Save patocl/a573269b00a129c0f0155bdb06b69bcd to your computer and use it in GitHub Desktop.
PluralSight Auto Play Behavior
const autoClickButton = (xpath) => {
// Checks if an element is visible on the page.
const isVisible = (element) => {
const style = window.getComputedStyle(element);
return style.display !== "none" && style.visibility !== "hidden" && style.opacity !== "0";
};
// Set up a MutationObserver to monitor DOM changes.
const observer = new MutationObserver(() => {
const button = document.evaluate(
xpath,
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE,
null
).singleNodeValue;
// If the button exists and is visible, click it.
if (button && isVisible(button)) {
button.click();
console.log(`Button clicked for XPath: ${xpath}`);
}
});
// Start observing the DOM for changes.
observer.observe(document.body, {
childList: true, // Monitors addition or removal of child nodes.
subtree: true, // Monitors changes in all descendant nodes.
});
};
// Clicks 'Next Lesson' button dynamically.
autoClickButton("//button[@aria-label='Next Lesson']");
// Clicks 'Start module' button dynamically.
autoClickButton("//button[contains(text(), 'Start module')]");
@patocl
Copy link
Author

patocl commented Nov 30, 2024

This script is designed to dynamically and repeatedly click buttons on a webpage with frequently updating content, such as in Single Page Applications (SPA). It leverages a MutationObserver to track changes in the DOM and react only when necessary. Here's what it does:

  1. Listens for DOM changes:
    It uses a MutationObserver to detect when the specified button is added to or reappears in the DOM.

  2. Validates button visibility:
    Before clicking, it ensures the button is visible on the page (i.e., not hidden, transparent, or removed).

  3. Continuously handles dynamic content:
    The script works persistently, clicking the button each time it appears or reappears.

  4. Reusability:
    The autoClickButton function accepts an XPath selector, making it adaptable to various buttons.

  5. Why is it more efficient than setInterval?
    Unlike setInterval, which repeatedly executes code at fixed intervals regardless of whether a button appears, MutationObserver reacts only when the DOM changes. This minimizes CPU usage, avoids unnecessary checks, and ensures the script works in sync with the dynamic updates of the page.


Enjoy it 😊

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