By accident I noticed a html button on a webpage which I could click programmatically as follows
button.click();
But when I did
const rect = btn.getBoundingClientRect();
const options = {
bubbles: true,
cancelable: true,
screenX: rect.x,
screenY: rect.y,
};
const e = new Event('click', options)
btn.dispatchEvent(e);
it didn’t work. Apparently there is a difference between the two. Can someone explain what that might be?
3
Answers
Both work for me
Notice that both of them have to be triggered by a user interation
The following experiment shows up a difference between the methods (there may be others):
pointerType: "mouse"
.click()
method produces an event withpointerType: ""
.pointerType: undefined
.Event can’t be used to click a submit button
A key piece of information is that the button on the page is a form submit button. This why the page reloads as noted in the question.
Both the click method and dispatchEvent will cause a click event. No problems with this part.
The actual problem is that OP is using a generic base Event to click a form submit button. This doesn’t work because the generic event won’t cause a submit event to be fired after the click.
Yet, if we instead use PointerEvent the form is submitted and the page reloads:
Test Snippet