jQuery click() not working in a Greasemonkey/Tampermonkey script

孤街醉人 提交于 2019-12-06 10:10:09

jQuery's .click() is just a shortcut for jQuery's .trigger() and from the Docs:

Any event handlers attached with .bind() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method.

This means that event-handlers, that are not set by jQuery, cannot always be triggered by .click() (or .trigger()).

To get around this, send actual mouse events:

jQuery ('button').each ( function () {
    jQuery (this).css ('background', 'red');

    var clickEvent  = document.createEvent ('MouseEvents');
    clickEvent.initEvent ('click', true, true);
    this.dispatchEvent (clickEvent);
}




Note that in some rare cases, the page will actually work off a combination of events, not the click, and that theoretically, pages can discriminate against any artificially produced event (though I've yet to see that in the wild).
If that is the case here, link to the target page so that we can make workaround(s).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!