javascriptgreasekit

If a button appears on a page, automatically click it


<a href="javascript:void(0)" class="PrmryBtnMed"
 id = "VERYLONGTEXT"

onclick="$(this).parents('form').submit(); return false;"><span>Dispatch to this address</span></a>

If I was to give instructions to a human, I would say:

  1. look for a <span>Dispatch to this address</span> link; if it appears click it. (if there is more than one such link (for example there are two) just click the first one (or any of them)

I am using Greasekit, so I am looking to do this using JavaScript.

Thank you!


Solution

  • Updated: Now checks contents of element

    var el = document.querySelector(".PrmryBtnMed"); //should only return first one
    if (el && (el.textContent.trim() == 'Dispatch to this address')) {
      el.click();
    } 
    

    Have a look at the querySelector and textContent for more information

    I also added a JsFiddle for you: http://jsfiddle.net/NrGVq/1/


    A different approach is to search the whole page, in case it's not inside the matched element

    var inPage = document.documentElement.innerHTML.indexOf('text to search') > 0,
        el = document.querySelector(".PrmryBtnMed");
    
    if (inPage && el) el.click();