How do I click on this button with Greasemonkey?

Here is a complete script that does that. It uses jQuery for the :contains() selector.

Update: Modified script to account for reported AJAX.

// ==UserScript==
// @name     _Click on a specific link
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require  https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a major design change
    introduced in GM 1.0.
    It restores the sandbox.
*/

//--- Note that contains() is CASE-SENSITIVE.
waitForKeyElements ("a.simplebutton:contains('follow')", clickOnFollowButton);

function clickOnFollowButton (jNode) {
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}

Note: in some cases the contains() term can trigger falsely. For example, if there is an <a class="simplebutton">unfollow</a> button.
Here’s one way to prevent false clicks. Modify the clickOnFollowButton function like so:

function clickOnFollowButton (jNode) {
    if ( ! /^\s*follow\s*$/i.test (jNode.text() ) ) {
        /*--- If the node contains anything but "follow" (surrounded by 
            optional whitespace), don't click it.
        */
        return false;
    }
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    jNode[0].dispatchEvent (clickEvent);
}

Several things:

  1. getElementsByClassName() returns a list or “collection” of elements. You can’t just .submit() its result like that. .submit() is for single elements.

  2. Since this is a link .submit() won’t work. .click() will often work, but often not — when a link is empowered by an event listener (which must be the case for this question).

    The clickEvent code, given above, works in almost all cases.

  3. The page code you gave does not have any link, with class="simplebutton" and text containing find!

  4. What Browser are you using? Which Greasemonkey version? And what OS?

  5. Find and use an appropriate javascript reference and an appropriate DOM reference. The reference listed in the question is for a library that is not standard and not included in your script (most likely).

    • The MDN JavaScript Reference is the most up-to-date and the most applicable for Greasemonkey (a Firefox extension) applications.
    • Likewise, the MDN Document Object Model (DOM) Reference.
  6. Use the CSS path, its much easier than XPATH, for this kind of thing. Firebug will show you the CSS path for a given element.
    jQuery uses CSS selectors/paths, as does document.querySelector() (a non jQuery approach).

Leave a Comment