IsTrusted Separates Real Events From DispatchEvent
Events built with new Event and dispatched from script always carry isTrusted false, so listener entry points can reject synthetic submissions early.
Code
// isTrusted is set by the user agent only: events built with new and dispatched
// from script are always false. In browsers, real user gestures produce true.
const bus = new EventTarget();
bus.addEventListener('payment', (event) => {
if (!event.isTrusted) {
console.log('rejected synthetic payment, isTrusted =', event.isTrusted);
return;
}
console.log('accepted payment');
});
// EventInit has no isTrusted field: constructor options cannot set it
bus.dispatchEvent(new Event('payment'));
bus.dispatchEvent(new CustomEvent('payment', { bubbles: true, cancelable: true }));
// The listener entry point is the only reliable filter; rewriting the flag fails
const forged = new Event('payment');
try {
forged.isTrusted = true; // getter-only: throws TypeError in module (strict) code
} catch (error) {
console.log('write rejected:', error.constructor.name);
}
console.log('flag still:', forged.isTrusted);Output
Captured from a sandboxed run of this snippet in the build pipeline.
rejected synthetic payment, isTrusted = false
rejected synthetic payment, isTrusted = false
write rejected: TypeError
flag still: falseWhat the demo rejects
Two events dispatched on the bus, a plain Event and a CustomEvent with full EventInit options, both fail the isTrusted check, because that flag is set by the user agent alone and EventInit has no field for it. The listener prints rejected synthetic payment for each.
The forgery attempt is equally futile: assigning forged.isTrusted = true throws TypeError in strict module code because the property is getter-only, and the printed flag stays false. The listener entry point is the only place the check can live.
Practical notes
- isTrusted is true only for events produced by real user gestures.
- The guard runs inside the listener, before any side effect.
Interactive Tools for This Topic
FAQ
- Can script set isTrusted to true?
- No; the property is getter-only and assigned by the user agent. The write throws TypeError and the flag remains false, as the printed lines show.
Report a problem with this exampleOpens a pre-filled issue on GitHub.