In order to determine if a click event was initiated by a user, you can utilize the event.isTrusted
property. Unfortunately, this feature has not been implemented yet.
However, there is an alternative approach to detect user-initiated events. The chrome.permissions.request
API requires a user gesture for success, otherwise it will fail. While using the chrome.permissions
API is restricted in content scripts post Chrome 33, the user gesture state remains preserved when utilizing the messaging API to communicate between a content script and the background page (since Chrome 36). To identify whether a click event was genuinely triggered by a user, you can implement the following logic:
background.js
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
if (message === 'is-user-gesture') {
chrome.permissions.request({}, function() {
// Check for errors to determine if the message was user-initiated
var is_user = !chrome.runtime.lastError;
sendResponse(is_user);
});
return true; // Async
}
});
contentscript.js
function isUserEvent(callback) {
chrome.runtime.sendMessage('is-user-gesture', function(is_user) {
// Take precaution as is_user may be undefined if extension is reloaded
is_user = is_user === true;
callback(is_user);
});
}
document.body.onclick = function() {
isUserEvent(function(is_user) {
alert(is_user ? 'Triggered by user' : 'Spoofed event');
});
};
To test this method, follow these steps within your page or content script:
// Simulate fake event (will show "Spoofed event")
document.body.dispatchEvent(new CustomEvent('click'));
// TODO: Click on the body with your mouse (will display "Triggered by user")