In this article, we will discuss about how to detect whether an event is triggered by actual user’s actions or forced triggering by a script.
Table of Contents
In the case of plain Javascript
By referencing the isTrusted property of the event object passed to the event listener’s callback, you can determine whether the event was triggered by an actual user action.
document.querySelector('#sample-btn').addEventListener('click', function(event){
if(event.isTrusted){
//actual user's actions
console.log('The user actually clicked the button')
}else{
//forced triggering by a script
console.log('The click event was forcibly triggered by a script')
}
})
document.querySelector('#sample-btn').dispatchEvent(new Event('click')) //forced triggering by a script
In the case of jQuery
In the case of jQuery, the the evaluation expression is bit difference, and it becomes as follows.
$('#sample-btn').on('click', function(event){
if(event.originalEvent?.isTrusted){
//actual user's actions
console.log('The user actually clicked the button')
}else{
//forced triggering by a script
console.log('The click event was forcibly triggered by a script')
}
})
//forced triggering by a script
$('#sample-btn2').click()
$('#sample-btn2').trigger('click')
$('#sample-btn2').get(0).dispatchEvent(new Event('click'))
For jQuery’s click and trigger methods, the event object lacks originalEvent, so you can avoid errors using optional chaining (?.).
Therefore, the evaluation expression is event.originalEvent?.isTrusted.
This is equivalent to event.originalEvent && event.originalEvent.isTrusted.
That is all, it was about how to detect if the Event is triggered by user’s action.