Detect Synthetic Clicks On A Webpage
Solution 1:
may be we can do something like this:
document.onmousedown = function(e) {
if (typeof(e.pageX) !== 'undefined' && e.pageX != 0)
{
alert ('human');
}else{
alert ('else');
}
}
or a similar approach:
document.onmousedown = function(e) {
if(e.screenX && e.screenX != 0 && e.screenY && e.screenY != 0){
alert("real button click");
}else{
alert("something else");
}
}
see here:Detect if button click real user or triggered by a script
Note: if you want a jquery solution visit this:Check if event is triggered by a human
Solution 2:
You can use vanilla Javascript as in the other anwsers or consider using jquery so you can easily detect non-human clicks.
1.Define a global click event handler using jquery.So you can catch all the clicks on page elements.
$(document).click(function(event) {
});
2.Check if the event.originalEvent is exists if it exists click was performed by a human. More info
For mouse clicks
$(document).click(function(event) {
if (event.originalEvent === undefined) {
alert('not human')
} else {
alert(' human');
}
});
For keypress
$(document).keypress(function(event) {
if (event.originalEvent === undefined) {
alert('not human')
} else {
alert(' human');
}
});
Here is a sample code.
<!DOCTYPE html><html><head><scriptsrc="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script>
$(document).ready(function(){
$(document).click(function(event) {
if (event.originalEvent === undefined) {
alert('not human')
} else {
alert(' human');
}
});
$(document).keypress(function(event) {
if (event.originalEvent === undefined) {
alert('not human')
} else {
alert(' human');
}
});
$(document).click();
$(document).keypress();
});
</script></head><body><p>Click me !</p></body></html>
Solution 3:
You'd probably want to watch for mousemove events and click events. If you're catching click events, but there are no mousemove events, I'd think it's safe to say that robots are clicking on your site.
Solution 4:
This is an old question but the accepted answer uses jQuery and I'm sure a lot of visitors here are looking for a vanilla JS solution. If you don't need to support IE, you can use Event.isTrusted
:
document.querySelector('a').onclick = function(event) {
if('isTrusted'in event) {
if(event.isTrusted === true) {
console.log('clicked on by a human');
} elseif(event.isTrusted === false) {
console.log('click was triggered by a script');
}
}
};
https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted
In IE, all events are trusted except those created by createEvent
:
https://technet.microsoft.com/en-us/windows/ff974948(v=vs.60)
Solution 5:
I realize this question is old but the correct way is to use event.isTrusted which will be true if user clicked with mouse or false if it was dispatched by a script.
Post a Comment for "Detect Synthetic Clicks On A Webpage"