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:
<p>
<input class="btn add-to-cart pull-left" name="add" id="add" value="Add to Cart" type="submit">
</p>
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 https://www.solefly.com/products/nike-hyperdunk-08-gym-red-white. 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:
document.querySelector('#add').click();
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.