自动选择值的 JavaScript 在 Firefox 控制台中有效,但在 Greasemonkey 脚本中不起作用

JavaScript to auto-select a value works in the Firefox console but not in Greasemonkey script?

本文关键字:有效 但在 Greasemonkey 不起作用 脚本 控制台 Firefox 选择 JavaScript      更新时间:2023-09-26

>我只想在表单中自动选择一个值。

以下代码在 Firebug 或 Firefox 控制台中有效,但在 Greasemonkey 用户脚本中不起作用:

document.getElementsByTagName('iframe')[2].contentWindow.document.getElementById("CDYN_126").value=1;

或:

window.frames["WA2"].document.getElementById("CDYN_126").value = 1;

我也尝试了setTimeoutwaitForKeyElements但没有任何效果。

这就是我尝试waitForKeyElements的方式:

function deneme.(){
    $("#WA2").contents().filter("#CDYN_126").val('1');
}
waitForKeyElements ("#WA2", deneme);


相关的渲染 HTML 如下所示:

<iframe scrolling="no" name="WA2" id="WA2" class="SCPIFRAMEMozilla">
    ...
    <select class="COMBOFIXSelectEdit" name="CC" id="CDYN_126" tabindex="1">
        <option value="0"></option>
        <option value="1">Ithal Ürün</option>
        <option value="2">Yerli Ürün</option>
        <option value="3">Güncellenecek</option>
    </select>
    ...
</iframe>


我做错了什么?

控制台具有提升的权限,包括对不一定与父页面来自同一来源的子框架的访问权限。

但是,用户脚本没有该权限,因此无法访问 iframe 的内容,除非它来自相同的协议、主机名和端口号。

您应该会在控制台中看到一条错误消息,告诉您这一点。

脚本没有等待 iframe 加载,这不是如何使用 waitForKeyElements() with an iframe .

waitForKeyElements.js 源页面中,参数为:

selectorTxt,/* 必需:jQuery 选择器字符串                    指定所需的元素。                */actionFunction,/* 必需:元素                    发现。它被传递给匹配的 jNode                    元素。                */bWaitOnce,/* 可选:如果为 false,将继续扫描                    即使在第一场比赛之后的新元素是                    发现。                */iframeSelector/* 可选:如果已设置,则将 iframe 标识为                    搜索。                */


您需要指定iframeSelector

根据问题代码,像这样的完整脚本将起作用:

// ==UserScript==
// @name     Site X, Auto-select imported products
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/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 ("#CDYN_126", deneme, false, "#WA2");
function deneme (jNode) {
    jNode.val ('1');
}