← 中文资源

简体中文版本

isTrusted 区分真实事件与脚本合成事件

脚本 new 出来再 dispatch 的事件 isTrusted 恒为 false,EventInit 里也没有这个字段。把检查放在监听器入口,合成提交直接拒绝;事后改写标志只会抛 TypeError。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

rejected synthetic payment, isTrusted = false
rejected synthetic payment, isTrusted = false
write rejected: TypeError
flag still: false

运行说明

向总线派发的两个事件——普通 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);