Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
510 views
in Technique[技术] by (71.8m points)

javascript - "Normal" button-clicking approaches are not working in Greasemonkey script?

Here is the button on the page:

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


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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

A general approach is given in Choosing and activating the right controls on an AJAX-driven site.

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


If it doesn't work for you, Link to the target page, or post an SSCCE!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...