Search code examples
javascriptjquerygoogle-chrome-extension

Programmatic clicks in javascript apparently not working


I am fiddling with a Chrome extension to add some extra capabilities to Gmail. For some steps I would need to programmatically click certain DOM elements. With some elements, this works fine and the expected action occurs. With others, however, there is no action at all, although manually clicking the same element results in specific action.

This behaviour is not caused by the element being loaded after the script, since I am using jQuery $(document).on() calls, and besides, the programmatic clicks are without effect also on the fully loaded page when executed from the console. I have also noted that the element does get clicked by my extension script, as detected by an added event listener.

Thus, it seems the page's original script manages to distinguish between manual clicks and programmatic ones. I wonder a) how this distinction is brought about b) and if there is a general strategy to circumvent it in the context of a browser extension.

I attach an example where I have tried to bring forth the label menu (this requires at least one message to be checked in the messages list) using console commands. An event listener is added to the element to be clicked, and then the element is clicked programmatically. This causes the listener to fire, but the label menu does not show up as it would have when the element is clicked manually.

Screenshot from Chrome Dev Tools


Solution

  • With the help of the reliable @wOxxOm, I have managed to clear some of the fogs around this issue. As was pointed out to me, the original script's event listeners might not be listening for "click" events, but rather for other events that also are triggered by a manual click, such as "mousedown". Which events are actually listened for can be gleaned from the devtools' Event Listeners tab (under Elements, se image).

    Devtools screenshot

    I was also given the good advice to use the dispatchEvent() statement to trigger the events rather than any jQuery variant – I could confirm that the latter were not working in this context. Some extra excitement was added by the fact that all elements do not have their own listeners, as they can be delegated to their parent element; and by the fact that some elements needed a sequential combination of "mousedown" and "mouseup" events in order for action to occur.