2012-11-07 2 views
1

captcha 입력 필드에 포커스를 자동으로 부여하는 Greasemonkey 스크립트를 작성하려고합니다. this example과 같이 captcha 양식을 동적으로 삽입하는 경우를 제외하고는 제대로 작동합니다. DOMNodeInserted에 대한 이벤트 리스너를 만드는 것이이 사건을 처리하기로되어 있다고 생각했습니다. (Firefox 17b에서 테스트 중입니다.)Greasemonkey 스크립트가 동적으로 삽입 된 위젯에 대해 작동하지 않습니다.

// ==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

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을 조심 (하지만 것을 테스트하지 않았습니다).

+0

MutationObservers를보고있는 Afert는 간단하고 많은 코드가 아닙니다. 그리고 범죄는 없지만 요령있는 스크립트에 의존하는 것에 조심 스럽습니다. – fipps

+0

요령 스크립트 코드는 완벽하게 볼 수 있으며 복잡하지 않습니다. 위험이 없다는 것을 쉽게 알 수 있습니다. 변경 될 수 있다고 염려되는 경우 원본을 스크립트에 붙여 넣거나 직접 제어 할 자유형 포크를 만듭니다. –

관련 문제