Detect auto-click on a page
Using document.onreadystatechange
will only work as expected in simple scenerios when no other third party libraries are included. Wrap you code inside the native DOMContentLoaded
event.
document.addEventListener("DOMContentLoaded",function(){
document.body.addEventListener('click', function(evt) {
if (evt.target.classList.contains('some-class')) {} // not used
console.log("which", evt.which);
console.log("isTrusted", evt.isTrusted);
}, true);
//this is the autoclick code!
el = document.getElementById('target');
if (el.onclick) {
el.onclick();
} else if (el.click) {
el.click();
}
console.log("clicked")
});
<html>
<head>
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<div id="target"> aaaaa </div>
</body>
</html>
If you look at the event param passed to the function on a click, or whatever other event, you can look for the following which is a telltale sign that the clicker ain't human...
event.originalEvent === undefined
From what you've said I'd use the following to track clicks...
$(document).on("click", function(event){
if(event.originalEvent.isTrusted){
//not human
}else{
//human
}
});
Can you check if both a click
event and either a mouseup
or touchend
event happen within 100 ms of each other? If they don't it's likely an automated event.
let mouseuportouchend = false;
let click = false;
let timer = null;
const regMouseupOrTouchend = function(){
mouseuportouchend = true;
if (!timer) timer = setTimer();
}
const regClick = function(){
click = true;
if (!timer) timer = setTimer();
}
const setTimer = function(){
timer = setTimeout(()=>{
if (click && mouseuportouchend) console.log("Manual");
else console.log ("Auto");
click=false;
mouseuportouchend=false;
timer=null;
}, 100)
}
let el = document.getElementById('target');
el.addEventListener("click",regClick);
el.addEventListener("mouseup", regMouseupOrTouchend);
el.addEventListener("touchend", regMouseupOrTouchend);