jQuery .click()
, like jQuery .trigger()
, only works reliably with events handled by jQuery. And in the case of userscripts and Greasemonkey scripts, the jQuery instance triggering click must be the same instance as the jQuery that set the event handler (usually).
Additionally, userscript jQuery interferes with the target page unless you explicitly take countermeasures.
There are two basic approaches in cases like this. (1) Use @grant none
mode, (2) properly sandbox your script and generate a true click event.
(1) Quick and dirty @grant none
method:
// ==UserScript==
// @name _YOUR_SCRIPT_NAME
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @grant none
// ==/UserScript==
var $ = window.jQuery;
$("a:contains('example')").click();
Warning: With this method, you cannot use the built-in GM_
functions. And, the page must be running jQuery to use jQuery functions.
(2) Recommended click event method:
// ==UserScript==
// @name _YOUR_SCRIPT_NAME
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
var targLink = $("a:contains('example')");
clickNode (targLink);
function clickNode (jNode) {
if (jNode && jNode.length) {
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
jNode[0].dispatchEvent (clickEvent);
}
}
Note that $(document).ready()
is not needed in Greasemonkey scripts except when @run-at document-start
is set.