.isTrusted
Example
payButton.addEventListener('click', () => {
submitPayment();
});payButton.addEventListener('click', (e) => {
if (!e.isTrusted) return;
submitPayment();
});Ignoring untrusted events blocks synthetic clicks from dispatchEvent(), though page scripts can still call the function directly.
Common mistakes
- Expecting
dispatchEvent(new MouseEvent('click'))to count as a user gesture.
Key points
- Sensitive actions check
event.isTrustedinstead of accepting any dispatched event. - Tests that need trusted events use browser automation input, since
dispatchEvent()events haveisTrustedfalse. - Code does not treat
isTrustedas bot protection; automation tools can produce trusted input.
Interview questions
Is element.click() a trusted event?
No, element.click() dispatches an event with isTrusted set to false, though it still runs the element's activation behavior.
Can I set isTrusted to true on my own event?
No, isTrusted is read-only, and only the browser sets it to true for real user or browser actions.
