XPath not working to click a button from a Greasem

2019-02-20 16:07发布

问题:

I would like to open a link that contains the word google. It looks like this:

 <input class="submit" style="background: #409999; border-radius: 10px;" value="open" onclick="Open('143615', '1', 'https://www.google.de/');" type="submit">


I tried this Greasemonkey code:

var snapResults = document.evaluate("//input[contains(@onclick, 'test')]",document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);

for (var i = snapResults.snapshotLength - 1; i >= 0; i--) {
    var elm = snapResults.snapshotItem(i);
    // do stuff with elm

    if (elm) //open the window, which contains "test"
    {
        elm.singleNodeValue.click(); //there is no effect ...
        alert(i+". element opend");
    }           
    else
    {
        alert(i+". Not found.");
    }
}

It has no effect. I would like to open the window via Greasemonkey (click event ?)

When I use alert(elm.href); it says it is "undefined". But the XPath works when I try it in FirePath.

回答1:

You say the XPath works, but elm.href is undefined in the GM script. This suggests that the <input> is added via AJAX.

Your script needs to use AJAX-aware techniques. Something like:

// ==UserScript==
// @name     _Clicking "Open" buttons
// @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 ("input.submit[onclick*='open']", clickOpenBtn);

function clickOpenBtn (jNode) {
    triggerMouseEvent (jNode[0], "click");
}

function triggerMouseEvent (node, eventType) {
    var clickEvent = document.createEvent ('MouseEvents');
    clickEvent.initEvent (eventType, true, true);
    node.dispatchEvent (clickEvent);
}