Search code examples
javascriptdom-eventsgreasemonkey

Using javascript to click on item with no href


Basically I am using the Firefox plugin called "greasemonkey" and I am attempting to write a script who's purpose is to find a specific class specified image on each page and click on it. Provided the item to be "clicked" has an href, this is accomplished fairly easily due to several other posts here, some using anchors and such, but assuming there is no href to follow, is there a way to "click" on an image or button?

For example, say I want to make my way through a survey and they have several check boxes or radio buttons. Is there a way to select the button using a script in greasemonkey?

For reference, this is what I have done in the past to "click" on a button that had a href attribute.

$("a.tip").each(function(){
if($(this).attr("caption")=="captionName"){
$.get("http://www.website.com" +$(this).attr("href"),window.location.reload());
return;
    }
});

*As far as the capabilities of greasemonkey, I am not certain what it can and can't do. diveintogreasemonkey.org appears it is no longer being hosted, therefore making the documentation fairly hard to come by.

Also, this would be different than a click listener because I am wanting the script to do the clicking. Any reference material you might have that could point me in the right direction would also be appreciated.

One last note, I am fairly new to this field of "web code" so if you would be so kind to explain it like I don't know anything, I won't be offended at all.


Solution

  • You can click on just about anything by generating an actual click event. No href is required and this technique is great for activating modern, javascript-powered controls on "web 2.0" sites.

    This method works even when .click() or jQuery's `.click() don't. (But, no method works on every control.)

    Plain JavaScript (Works on Firefox, Chrome, Greasemonkey,and others):

    var clickTarget = document.querySelector ("Any valid CSS selector");
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    clickTarget.dispatchEvent (clickEvent);
    


    jQuery version:

    var clickTarget = $ ("Any valid jQuery selector");
    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    clickTarget[0].dispatchEvent (clickEvent);
    


    Note that both of these snippets are for one link/button/etc. at a time.
    On AJAX-driven pages, be sure you check that the target node exists first, and wait if necessary.