Sam M Sam M - 1 year ago 113
Javascript Question

How to click in GreaseMonkey

I am trying to click a button in Greasemonkey.
I have tried two different types of code:

var evt = document.createEvent ("HTMLEvents");
evt.initEvent ("click", true, true);
document.getElementById('BIS_trigger').dispatchEvent (evt);

And secondly,

var checkoutBtn = document.querySelector (
"add input"
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
checkoutBtn.dispatchEvent (clickEvent);

I have had experience with c# and programming before, but am really new with Greasemonkey.

The html:

<input class="btn add-to-cart pull-left" name="add" id="add" value="Add to Cart" type="submit">

When I enable the little check mark next to the name of my script in my browser then reload, nothing happens. Is it because the thing I am trying to click is an "input"?

If you want to check it out for yourself please go to the site Thanks!

Answer Source

You don't need to synthesise the event, you can just call the click() method on the button. However, your selector is wrong and so you don't actually find the button:

You can do this, finding the button via its id property:


Note that your selector add input searches for a tag with name add (which obviously is not there), and then would search for a descendant input element under that add element. As id values are supposed to be unique in an HTML document, you can use a selector on id, which requires the # prefix.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download