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

我是研究僧i 提交于 2019-12-07 22:56:25

问题


I am having issues triggering a jQuery click through Greasemonkey/Tampermonkey...

jQuery('button').each(function() {
    jQuery(this).css('background', 'red');
    jQuery(this).click();
    location.assign("javascript:jQuery(this).click();void(0)");
}​

As you can see I've even tried the location.assign hack but nothing will work, no errors in the console either.

Funny thing is that yes, the background colour does change to red so I am assuming it's something in the way .click() works that is different from other jQuery methods.


回答1:


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).



来源:https://stackoverflow.com/questions/10423426/jquery-click-not-working-in-a-greasemonkey-tampermonkey-script

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