AJAX 요청 시 Greasemonkey 스크립트를 실행합니다.
사용자 스크립트를 작성 중인데 메인 페이지가 AJAX 요청을 할 때 스크립트가 실행되지 않는 것을 알게 되었습니다.
메인 페이지 로드 시 및 AJAX 요청 시 모두 사용자 스크립트를 실행할 수 있는 방법이 있습니까?
AJAX 요청에서 스크립트의 코드를 재실행하는 현명한 방법은 페이지의 키 비트에 초점을 맞추고 변경을 확인하는 것입니다.
예를 들어 다음과 같은 HTML이 페이지에 포함되어 있다고 가정합니다.
<div id="userBlather">
<div class="comment"> Comment 1... </div>
<div class="comment"> Comment 2... </div>
...
</div>
댓글 올 때마다 대본이 뭔가를 해주길 원했잖아요
이제 모든 AJAX 호출을 가로챌 수 있고
또는 듣거나 (권장되지 않음) 또는 사용DOMSubtreeModified
MutationObserver단, 이러한 방법은 까다롭고 까다롭고 지나치게 복잡할 수 있습니다.
와일드 페이지에서 Ajax로 분류된 콘텐츠를 얻는 보다 간단하고 강력한 방법은 다음과 같은 방법을 사용하여 폴링하는 것입니다.waitForKeyElements함수, 아래.
예를 들어, 이 스크립트는 "beer"가 포함된 코멘트를 강조 표시합니다(AJAX-in:
// ==UserScript==
// @name _Refire on key Ajax changes
// @include http://YOUR_SITE.com/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
function highlightGoodComments (jNode) {
//***** YOUR CODE HERE *****
if (/beer/i.test (jNode.text () ) ) {
jNode.css ("background", "yellow");
}
//...
}
waitForKeyElements ("#userBlather div.comment", highlightGoodComments);
/*--- waitForKeyElements(): A utility function, for Greasemonkey scripts,
that detects and handles AJAXed content.
IMPORTANT: This function requires your script to have loaded jQuery.
*/
function waitForKeyElements (
selectorTxt, /* Required: The jQuery selector string that
specifies the desired element(s).
*/
actionFunction, /* Required: The code to run when elements are
found. It is passed a jNode to the matched
element.
*/
bWaitOnce, /* Optional: If false, will continue to scan for
new elements even after the first match is
found.
*/
iframeSelector /* Optional: If set, identifies the iframe to
search.
*/
) {
var targetNodes, btargetsFound;
if (typeof iframeSelector == "undefined")
targetNodes = $(selectorTxt);
else
targetNodes = $(iframeSelector).contents ()
.find (selectorTxt);
if (targetNodes && targetNodes.length > 0) {
btargetsFound = true;
/*--- Found target node(s). Go through each and act if they
are new.
*/
targetNodes.each ( function () {
var jThis = $(this);
var alreadyFound = jThis.data ('alreadyFound') || false;
if (!alreadyFound) {
//--- Call the payload function.
var cancelFound = actionFunction (jThis);
if (cancelFound)
btargetsFound = false;
else
jThis.data ('alreadyFound', true);
}
} );
}
else {
btargetsFound = false;
}
//--- Get the timer-control variable for this selector.
var controlObj = waitForKeyElements.controlObj || {};
var controlKey = selectorTxt.replace (/[^\w]/g, "_");
var timeControl = controlObj [controlKey];
//--- Now set or clear the timer as appropriate.
if (btargetsFound && bWaitOnce && timeControl) {
//--- The only condition where we need to clear the timer.
clearInterval (timeControl);
delete controlObj [controlKey]
}
else {
//--- Set a timer, if needed.
if ( ! timeControl) {
timeControl = setInterval ( function () {
waitForKeyElements ( selectorTxt,
actionFunction,
bWaitOnce,
iframeSelector
);
},
300
);
controlObj [controlKey] = timeControl;
}
}
waitForKeyElements.controlObj = controlObj;
}
업데이트:
편의상waitForKeyElements()현재 GitHub에서 호스팅되고 있습니다.
이 답변은 호스트 기능을 사용하는 방법의 예를 보여 줍니다.
또 다른 방법(간단하고 작지만 유연성이 떨어지는)은 JavaScript 시간 지연을 사용하여 AJAX/jQuery가 로드되어 완료될 때까지 기다리는 것입니다.예를 들어 첫 번째 로드 후 다음 HTML이 동적으로 생성된 경우:
<div id="userBlather">
<div class="comment"> Comment 1... </div>
<div class="comment"> Comment 2... </div>
...
</div>
그런 다음 다음과 같은 greasemonkey 스크립트를 수정할 수 있습니다.
// Wait 2 seconds for the jQuery/AJAX to finish and then modify the HTML DOM
window.setTimeout(updateHTML, 2000);
function updateHTML()
{
var comments = document.getElementsByClassName("comment");
for (i = 0; i < comments.length; i++)
{
comments[i].innerHTML = "Modified comment " + i;
}
}
여기: Javascript의 sleep/pause/wait 안내 참조
언급URL : https://stackoverflow.com/questions/8281441/fire-greasemonkey-script-on-ajax-request
'source' 카테고리의 다른 글
| AWS: ID 풀 구성이 잘못되었습니다.이 풀에 대해 할당된 IAM 역할 확인 (0) | 2023.02.15 |
|---|---|
| 각도 루트의 htaccess 리다이렉트 (0) | 2023.02.15 |
| 여기서 'it()' 함수는 무엇을 하고 있습니까? (0) | 2023.02.15 |
| Postgres에서의 JSON과 JSONB의 차이점 (0) | 2023.02.15 |
| png 파일을 webp 파일로 변환하는 방법 (0) | 2023.02.15 |