运行说明
向总线派发的两个事件——普通 Event 与带完整 EventInit 的 CustomEvent——都过不了 isTrusted 检查:该标志只由用户代理设置,EventInit 没有对应字段。监听器为每个事件打印 rejected synthetic payment。
伪造同样徒劳:在 strict 模块代码里给 forged.isTrusted 赋 true 抛 TypeError(属性只有 getter),打印的标志仍是 false。这个检查只能放在监听器入口。
要点提示
- isTrusted 只有真实用户手势产生的事件才为 true。
- 守卫在监听器内、任何副作用之前执行。
核心语句
if (!event.isTrusted) {
代码示例
// 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);