Search code examples
javascriptpopupui-automation

How to trigger the onclick function by code by writing an javascript extension?


There's this website that logs me off if I don't click a button in a form that periodically pops up. I'd like to write a script to automate this.

What's the phrase that describes such web task automation?

How do I detect such pop up?

How do I trigger the onclick function in that form via code?


Solution

  • Usually, all you need is to be able to identify a unique selector for the element. When you see the button appear, right-click it and Inspect it in the Elements panel of your browser. Look for something that makes it unique, such as an ID, or a class (that no other button has), or being a descendant of a similar unique container.

    For example, the "Post Your Answer" button on Stack Exchange has an ID of submit-button, so you can select it with #select-button:

    enter image description here

    Once you have the selector, either periodically check for it in an interval, or use MutationObserver (more complicated and more expensive, but it'll click the button ASAP, and doesn't require polling). Whenever the element exists, .click() it.

    setInterval(() => {
      const elm = document.querySelector('#my-btn');
      if (elm) {
        elm.click();
      }
    }, 1000);
    

    You might find it easier to put this code into a userscript rather than a standalone Chrome extension - userscripts are far easier to manage IMO, all you need to do is type the Javascript and it's ready to go.