XPath无法从Greasemonkey脚本单击按钮 [英] XPath not working to click a button from a Greasemonkey script

查看:92
本文介绍了XPath无法从Greasemonkey脚本单击按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打开一个包含单词 google 的链接。看起来像这样:

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



我尝试了以下Greasemonkey代码:


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

它没有效果。我想通过Greasemonkey打开窗口(单击事件?)

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

当我使用 alert(elm.href); 它说它是未定义的。但是当我在 FirePath 中尝试XPath时,它就可以工作。

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

推荐答案

您说XPath可以,但是GM脚本中未定义 elm.href 。这表明< input> 是通过AJAX添加的。

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

您的脚本需要使用支持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);
}

这篇关于XPath无法从Greasemonkey脚本单击按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆