Sam M Sam M - 5 months ago 27
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!


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.