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

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

Leave a Comment