Clicking a button on a page using a Greasemonkey/userscript in Chrome

試著忘記壹切 提交于 2019-11-27 16:10:47

Note:

  1. jQuery .click() does not work reliably on click events that were not set via jQuery in the first place.

  2. You need to create the right kind of event; createEvent('Events') is not the way.

  3. As Jim Deville pointed out, the link pseudo-button was not being selected.

  4. You do not need jQuery for this (so far).

  5. Make sure that the "Refresh" control is loaded statically for the test code as shown in the question. If it's AJAXed in, the click attempt may fire too soon.

Putting that all together, the following code should work. But beware that some sites (like certain Google apps) use funky, state-sensitive designs -- which require a sequence of events.

var refreshBtn = document.querySelector (
    "div.serverguide-header-refresh-button div[type='reset'] a"
);
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
refreshBtn.dispatchEvent (clickEvent);

so, you are on the right track, but you keep grabbing the DIV not the A tag. To click on the "button" (link in this case), you have to click on the actual link because it won't tunnel down to the elements contained in the DIV.

document.querySelector('serverguide-header-refresh-button a')

Should get you the A element to click on. From jQuery $('serverguide-header-refresh-button a').click(); should work.

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