Search code examples
javascripttampermonkey

Tampermonkey script to check for a button and click it


I am pretty new to creating scripts with tampermonkey and even after looking at several answers for the past few hours I still cant figure this one out.

I'm trying to make a script that checks for a button and when it appears for it to click it after about 2 seconds.

I am trying to search it by ID like this:

    var caseHide = document.getElementById("accept");
var checkTimer = setInterval(MyTimer, 1500);

function MyTimer() {
  if (caseHide.offsetParent === null)
    {
      return;
    }
  var eek = document.getElementById("accept");
  var evt = document.createEvent("MouseEvents");
  evt.initEvent("click", true, true);
  eek.dispatchEvent(evt);
}

checkTimer();

However when the button appears it's not being clicked.

I also must mention that this is a button that appears without a set interval because it's prompted by an alert, and as such I can't really say how often it will appear.


Solution

  • A few thoughts.

    The first getElementById will probably fail since that button likely does not exist yet.

    Also, simply searching for #accept might not be enough to actually locate the element. It depends what your page looks like.

    Here's what I do. In DevTools console, do this:

    document.getElementById('accept').length
    

    If it comes back undefined, then your css selector is not specific enough. You may have to walk the tree a bit more... something like:

    document.querySelector('body #main .prevDiv #accept')
    

    Do you know what I mean? Starting farther up the tree and walking down to the element. If it doesn't work in DevTools, it won't work in TamperMonkey. In modern libraries like Angular/React/Svelte/etc, you might have more than one element with the same ID... so just specifying the single element might not find it.

    Then, your function can look like this:

    var checkTimer = setInterval(MyTimer, 1500);
    checkTimer();
    
    function MyTimer() {
       const eek = document.getElementById("accept");
       if (eek !== undefined){
          const evt = document.createEvent("MouseEvents");
          evt.initEvent("click", true, true);
          eek.dispatchEvent(evt);
       }
    }
    
    

    References:

    https://www.youtube.com/watch?v=Pr4LLrmDLLo

    https://www.youtube.com/watch?v=SowaJlX1uKA