[英]Greasemonkey script not working against dynamically inserted widget
我正在嘗試編寫一個Greasemonkey腳本,如果找到該腳本,它將自動為驗證碼輸入字段提供焦點。 像在本示例中那樣,動態插入驗證碼表單的情況下,此方法工作正常。 我認為為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);
DOMNodeInserted
是一個Mutation事件,並且不推薦使用Mutation事件是有充分理由的。 該代碼可能會嚴重加載瀏覽器的JS,並可能觸發某些“腳本繁忙/失控”保護措施。
您可以切換到全新的MutationObservers ,但這對於這種事情來說太過復雜了。
使用久經考驗的waitForKeyElements()實用程序 。 像這樣:
// ==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 可能會使事情復雜化(盡管尚未進行測試)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.