Skip to content
Advertisement

Can a Chrome extension’s content script guarantee that a DOM event was user-initiated?

I have an extension injecting HTML elements into pages and watching for click events on those elements. I want to be sure that any given click event came from a user action, rather than JS on the page creating and dispatching a click event. Is there a way of doing so?

Advertisement

Answer

You’re looking for event.isTrusted, which has not yet been implemented.

But it is still possible to detect whether a click event was user-initiated. The chrome.permissions.request API requires a user gesture, or else it will report a failure. The chrome.permissions API cannot be used in content scripts (since Chrome 33). Fortunately, the user gesture state is preserved when you use the messaging API to exchange a message from a content script and the background page (Since Chrome 36). So, you can use the following logic to detect whether the click event was generated by a user and act accordingly:

background.js

JavaScript

contentscript.js

JavaScript

To test this method, run the following steps in the page / content script:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement