How to check trusted events
JS Bits Bill
Posted on June 15, 2021
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');
});
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();
or
btn.dispatchEvent(new MouseEvent('click'));
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:
Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter and TikTok!
💖 💪 🙅 🚩
JS Bits Bill
Posted on June 15, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript How I Created Vanilla Calendar Pro — A Lightweight and Flexible JavaScript Calendar with TypeScript
November 28, 2024