“正常”按钮单击方法在Greasemonkey脚本中不工作?
问题描述:
这是页面上的按钮:
<a id="dispatchOnJobButton" class="ui-btn ui-btn-corner-all ui-shadow ui-btn-up-c" href="#" data-role="button" data-theme="c" data-disabled="false">
<span class="ui-btn-inner ui-btn-corner-all" aria-hidden="true">
<span class="ui-btn-text">Dispatch on next job</span>
</span>
</a>
我需要Greasemonkey才能点击它。我尝试了很多不同的方法,但没有一个似乎触发任何函数应该运行。
I need Greasemonkey to click it. I tried many different methods, but none seem to fire whatever function it is supposed to run.
var clickEvent = document.createEvent("MouseEvents");
clickEvent.initEvent("click", true, true);
document.getElementById('dispatchOnJobButton').dispatchEvent(clickEvent);
// also tried
document.getElementById('dispatchOnJobButton').click();
// and this
unsafeWindow.document.getElementById('dispatchOnJobButton').click();
我可以尝试的其他任何想法吗?
any ideas on something else I could try?
答
不是每个按钮都可以实现点击事件。此外,还不清楚这是一个静态加载的按钮,还是由AJAX加载的。 (链接到目标网页!)
Not every button works off a click event. Also, it's not clear if this is a statically loaded button, or if it's loaded by AJAX. (Link to the target page!)
一般方法在在AJAX驱动的网站上选择并激活正确的控件。
这样的完整脚本会在99%的情况下工作:
Something like this complete script will work in 99% of the cases:
// ==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
// @require https://gist.github.com/raw/2625891/waitForKeyElements.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.
*/
waitForKeyElements ("#dispatchOnJobButton", triggerMostButtons);
function triggerMostButtons (jNode) {
triggerMouseEvent (jNode[0], "mouseover");
triggerMouseEvent (jNode[0], "mousedown");
triggerMouseEvent (jNode[0], "mouseup");
triggerMouseEvent (jNode[0], "click");
}
function triggerMouseEvent (node, eventType) {
var clickEvent = document.createEvent('MouseEvents');
clickEvent.initEvent (eventType, true, true);
node.dispatchEvent (clickEvent);
}
如果它不适合你, 链接到目标网页,或发布 SSCCE!
If it doesn't work for you, Link to the target page, or post an SSCCE!