Building a web game in my spare time and people have been using auto clickers to do things I don't intend.
This is an extremely dumbed down example:
button1.onclick = handleButton1Click
button2.onclick = handleButton2Click
What I want to to is prevent untrusted clicks and really HOPED this method wouldve worked:
button1.onclick = handleButton1Click
button2.onclick = handleButton2Click
window.onclick = e => {
if (!e.isTrusted) {
e.stopPropagation()
return false
}
}
But this doesn't do what I'm looking for, for what I'm assuming is because they're separate events.
Is there something I can do besides doing the isTrusted check on every click event?
You can follow the approach you had, but instead of listening globally you can wrap your calls so you can do the check on the actual click.
const button1 = document.querySelector('#button1');
const button2 = document.querySelector('#button2');
const handleButton1Click = (evt) => {
console.log("1", evt.target);
evt.currentTarget.classList.toggle('active');
}
const handleButton2Click = (evt) => {
console.log("2", evt.target);
evt.currentTarget.classList.toggle('active');
}
const clean = (fnc) =>
(e) => {
if (!e.isTrusted) {
console.log('blocked');
e.stopPropagation()
return false
}
return fnc(e);
}
button1.onclick = clean(handleButton1Click);
button2.onclick = clean(handleButton2Click);
button1.click();
button1.click();
button2.click()
.active {
color: yellow;
background-color: lime;
}
<button id='button1'>button1</button>
<button id='button2'>button2</button>
You can throttle the calls here too so a user can not click it more than once every X milliseconds.