Greasemonkey脚本无法对抗动态插入的小部件

时间:2012-11-07 21:20:28

标签: javascript greasemonkey

我正在尝试编写一个Greasemonkey脚本,如果找到,它会自动将焦点放在验证码输入字段上。除了动态插入验证码表单(例如this example)之外,这种方法很好。我认为为DOMNodeInserted创建一个事件监听器应该处理这种情况。 (我正在测试Firefox 17b)。

// ==UserScript==
// @name          Focus captcha field
// @description   Adds focus on captcha fields
// ==/UserScript==

function focusCaptcha (elem) {
    var ids = ['recaptcha_response_field', 'adcopy_response', 'captcha_input'];
    for (var i = ids.length - 1; i >= 0; i--) {
        var input = elem.getElementById(ids[i]);
        if (input) {
            input.focus();
            input.value = '';
            return;
        }
    }
}

(function() {
    focusCaptcha(document);
})();

document.addEventListener('DOMNodeInserted', function(event) {
    focusCaptcha(event.target);
}, false);

1 个答案:

答案 0 :(得分:1)

DOMNodeInserted是一个变异事件Mutation Events are deprecated,这是有充分理由的。该代码可能会严重加载浏览器的JS并可能触发一些“脚本忙/失控”保护措施。

你可以切换到全新的MutationObservers,但对于这类事情来说这是一种复杂的过度杀伤。

使用久经考验的waitForKeyElements() utility。像这样:

// ==UserScript==
// @name        _Focus captcha field
// @description Adds focus on captcha fields
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/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.
*/

function focusCaptcha (jNode) {
    jNode.val ('');
    jNode[0].focus ();
}

waitForKeyElements (
    "#recaptcha_response_field, #adcopy_response, #captcha_input#",
    focusCaptcha
);

请注意,在尝试移动焦点时,iframe 可能会使事情变得复杂(尽管尚未对此进行测试)。

相关问题