在AJAX请求上重新运行脚本代码的明智方法是,专注于页面的关键部分并检查更改。
例如,假设页面包含如下所示的HTML:
<div id="userBlather"> <div > Comment 1... </div> <div > Comment 2... </div> ... </div>
并且您希望脚本对每个注释进行处理。
现在,您 可以 拦截所有AJAX调用,或者侦听(不建议使用)或使用DOMSubtreeModified
MutationObservers,但是这些方法可能会变得棘手,挑剔且过于复杂。
在通配页上获取ajax形式的内容的一种更简单,更可靠的方法是使用
waitForKeyElements下面的函数对其进行轮询。
例如,此脚本将在AJAX中突出显示包含“啤酒”的注释:
// ==Userscript==// @name _Refire on key Ajax changes// @include http://YOUR_SITE.com/YOUR_PATHfunction waitForKeyElements ( selectorTxt, actionFunction, bWaitOnce, iframeSelector ) { var targetNodes, btargetsFound; if (typeof iframeSelector == "undefined") targetNodes = $(selectorTxt); else targetNodes = $(iframeSelector).contents () .find (selectorTxt); if (targetNodes && targetNodes.length > 0) { btargetsFound = true; 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;}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)