DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

2 1

How to check trusted events

How would one check if an event was triggered by an actual user action and not from a script or dispatched event? Well, there's an isTrusted property on Event objects:

btn.addEventListener('click', event => {
  if (!event.isTrusted) {
    return console.log('Not trusted!');
  }

  console.log('Proceed');
});
Enter fullscreen mode Exit fullscreen mode

Here we are checking if event.isTrusted is false and if so, return out. isTrusted will only be true when the click event is done via a real mouse click and not with a proxy click via:

btn.click();
Enter fullscreen mode Exit fullscreen mode

or

btn.dispatchEvent(new MouseEvent('click'));
Enter fullscreen mode Exit fullscreen mode

If you want to make sure certain interactions can only be accomplished by user behavior and not via scripts (i.e. browser extensions) Event.isTrusted can help add an extra layer of security! 🔒

Here's a video on using the isTrusted property:


isTrusted TikTok


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter and TikTok!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (1)

Collapse
 
dailydevtips1 profile image
Chris Bongers

Interesting, never seen this used, but it would make sense in certain cases!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay